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

Answer:

Because the instance variables director, and rating are members only of Movie objects, so code defined in Video cannot use them.


Overriding Methods

We need a new toString() method in the class Movie:

// added to class Movie
public String toString()
{
  return getTitle() + ", " + getLength() + " min. available:" + getAvailable() +
         " dir: " + director + ", rating:  " + rating ; 
}

Now, Movie has its own toString() method that uses variables it inherits and variables it defines.

Even though the parent has a toString() method, the new definition of toString() in the child class will override the parent's version. It is used when a String based on the child object is needed.

A child's method overrides a parent's method when it has the same signature as a parent method. Now the parent has its method, and the child has its own method with the same signature. (Remember that the signature of a method is the name of the method and its parameter list.)

An object of the parent type includes the method given in the parent's definition. An object of the child type includes both the method given in the parent's definition and the method given in the child's definition. The parent's method can be invoked using super. (See below.)

With the change in the class Movie the following program will print out the full information for both items.


class VideoStore
{
  public static void main ( String args[] )
  {
    Video item1 = new Video("Microcosmos", 90 );
    Movie item2 = new Movie("Jaws", 120, "Spielberg", "PG" );
    System.out.println( item1.toString() );
    System.out.println( item2.toString() );
  }
}

The line item1.toString() calls the toString() method defined in Video, and the line item2.toString() calls the toString() method defined in Movie.

Microcosmos, 90 min. available:true
Jaws, 120 min. available:true dir: Spielberg PG, rating: PG

QUESTION 16:

Would the following main() work? (toString() has been removed.)

class VideoStore
{
  public static void main ( String args[] )
  {
    Video item1 = new Video("Microcosmos", 90 );
    Movie item2 = new Movie("Jaws", 120, "Spielberg", "PG" );
    System.out.println( item1 );
    System.out.println( item2 );
  }
}

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