Overriding Methods

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

Because the class Video does not define the instance variables director and rating, so its show() method can't use them.

Overriding Methods

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

// added to class Movie
public void show()
{
  System.out.println( title + ", " + length + " min. available:" + avail );
  System.out.println( "dir: " + director + "  " + rating );  
}

Now, even though the parent has a show() method the new definition of show() in the child class will override the parent's version.

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 the method given in the child's definition.

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" );
    item1.show();
    item2.show();
  }
}

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

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

QUESTION 15:

Does the definition of show() in the Movie class include some code that is already written?