go to previous page   go to home page   go to next page hear noise highlighting

Answer:

(Review:) How can you write a class with a no-argument constructor?

One way to do this is to explicitly write a constructor that takes no arguments.


Creating a no-argument Constructor

Details:

  1. You can explicitly write a no-argument constructor for a class.
  2. If you do not write any constructors for a class, then a no-argument constructor (called the default constructor) is automatically supplied.
  3. If you write even one constructor for a class then the default constructor is not automatically supplied.
  4. So: if you write a constructor for a class, then you must also write a no-argument constructor if one is expected.

In the example program, the class definition for Video includes a constructor, so the default constructor was not automatically supplied. So the constructor proposed for Movie (that automatically calls a no-arg constructor) causes a syntax error.

So the proposed constructor will not work. The fix would be to explicitly put a no-argument constructor in class Video as follows:

class Video
{
  private String  title;    // name of the item
  private int     length;   // number of minutes
  private boolean avail;    // is the video in the store?

  // no-argument constructor
  public Video()
  {
    title = new String( "" ); length = 90; avail = true; 
  }

  // constructor
  public Video( String ttl )
  {
    title = ttl; length = 90; avail = true; 
  }

  // constructor
  public Video( String ttl, int lngth )
  {
    title = ttl; length = lngth; avail = true; 
  }
  . . . 

}

But this is a sloppy design, included here only to show an aspect of inheritance.

Let's go back to the original design of class Movie without the proposed constructor.


QUESTION 14:

Why is the proposed design sloppy?


go to previous page   go to home page   go to next page