Chapter 9
More about inheritance

powered by FreeFind

Modified: 

Overview

Chapter 8 introduced inheritance. Chapter 9 discusses key elements of inheritance - method overriding and polymorphism.

overriding - A subclass method of the same name as a super class method will be called for the subclass object. The sub class method has precedence over the super class method.

Method Polymorphism - When a method is overridden (i.e. methods with the same name in an inheritance hierarchy), the object's class determines which of the methods is called.

Invokes the printTicket() method at line 37.

Invokes the printTicket() method at line 16.

  1.  public class TicketMachine
  2.  {
  3.     private int price;
  4.     private int balance;
  5.     private int total; 
     
  6.     public TicketMachine(int ticketCost)
  7.    {
  8.        price = ticketCost;
  9.        balance = 0;
  10.        total = 0;
  11.     }
     
  12.    public void insertMoney(int amount)
  13.    {
  14.        balance += amount;
  15.    }
     
  16.    public void printTicket()
  17.    {
  18.        System.out.println("# " + price +
                                      " cents.");
     
  19.        total += balance;
  20.        balance = 0;
  21.    }
  22. }
  1. public class BusTicketMachine extends TicketMachine
  2. {
  3.     private String bus, stops;
     
  4.     public BusTicketMachine( int theCost, String theBus,
                                           String theStops )
  5.     {
  6.           super( theCost );
  7.           bus = theBus;
  8.           stops = theStops;
  9.      }
     
  10.      public void printStops()
  11.      {
  12.          System.out.println("# Bus " + bus );
  13.          System.out.println("# Stops " + stops );
  14.      }
     
  15.      public void printTicket()
  16.      {
  17.          System.out.println("# Ticket for bus  " + bus );
  18.          super.printTicket();
  19.      } 
  20. }
             
Exercise 0a - Method Polymorphism

Suppose that we have created TicketMachine and BusTicketMachine by:

BusTicketMachine tm1 = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );

TicketMachine t2 = new TicketMachine( 60 );

TicketMachine t3 = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );

  1. Are the following valid?

    tm1.printStops();

    tm2.printStops();

    tm3.printStops();

     

  2. Trace the execution of:

    tm1.printTicket();

    tm2.printTicket( );

    tm3.printTicket( );

 

One Two Three
  1. public class One
  2. {
  3.    private String oneS;
     
  4.    public One(String theS)
  5.    {
  6.       oneS = theS;
  7.    }
     
  8.    public String getS()
  9.    {
  10.        return oneS;
  11.    }
  12. }
  1. public class Two extends One
  2. {  
  3.     private String twoS;
     
  4.     public Two(String theS)

  5.    {

  6.       super("red");

  7.       twoS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return twoS;
  12.    }
  13. }
  1. public class Three extends Two
  2. {
  3.    private String threeS;
     
  4.    public Three(String theS)

  5.    {

  6.       super("blue");

  7.       threeS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return threeS;
  12.    }
  13. }
Exercise 0b - Polymorphism
  • What is the hierarchy?
  • Trace the execution.
   One myOne     = new Two("red");
   Two myTwo     = new Three("white");
   Three myThree = new Three("blue");

   System.out.print( myOne.getS() );
   System.out.print( myTwo.getS() );
   System.out.print( myThree.getS() );


9 Introduction

You may have noticed that the second DoME example that used inheritance did not print all the data fields of CD and Video. Only the fields of Item class were printed. The reason being that the Item method print() only has access to Item fields.

Database list() method calls:

Item item = (Item) iter.next();
item.print();

Item Video CD
public class Item
{
   private String title;
   private int playingTime;
   private boolean gotIt;
   private String comment;

    public void print()
   {
      System.out.print("title: " + title +
               " (" + playingTime + " mins)");
      if(gotIt) {
         System.out.println("*");
      } else {
         System.out.println();
      }
      System.out.println(" " + comment);
   }

public class Video extends Item
{
   private String director;

:
:

public class CD extends Item
{
   private String artist;
   private int numberOfTracks;

:
:

public class Database
{
   private ArrayList items;

   public void list()
   {
      for(Iterator iter = items.iterator(); iter.hasNext(); )
      {
         Item item = (Item)iter.next();
         item.print();
      }
   }
}
Exercise 1 - DoME print problem

In BlueJ

  • Open chapter08/dome-v2
  • Create a Video, CD and Database object.
    • Use Database method addItem() to add the CD and Video object to the database.
  • Call the Database method list() to print the database.
    • Did the Item method print() execute?

     

  • Add print() methods for CD and Video classes.
    • Copy and paste print() from below.
  • Create a Video, CD and Database object.
    • Use Database method addItem() to add the CD and Video object to the database.
  • Call the Database method list() to print the database.
    • Did the Item method print() execute?
Item Video CD
public class Item
{
 private String title;
 private int playingTime;
 private boolean gotIt;
 private String comment;

 public void print()
 {
   System.out.print("title: " + title +
          " (" + playingTime + " mins)");
   if(gotIt) {
       System.out.println("*");
   } else {
      System.out.println();
   }
   System.out.println(" " + comment);
 }

public class Video extends Item
{
   private String director;

 


   public void print()
   {
      System.out.println("Video " +
                 director);
   }

:
:

public class CD extends Item
{
   private String artist;
   private int numberOfTracks;



   public void print()
   {
      System.out.println("CD " + artist);
      System.out.println(" tracks: " +
                           numberOfTracks);
   }

:
:


9.2 Static type and dynamic type

Problem

Solution


9.2.1 Calling print from Database

Database list() method calls:

  public void list()
   {
      for(Iterator iter = items.iterator(); iter.hasNext(); )
      {
         Item item = (Item) iter.next();                               // item is CD or Video
         item.print();                                                          // Call CD or Video print() method
      }
   }

static type - The type a variable is declared in the Java source code. Used for type checking at compile time. 
dynamic type - The type a variable stores at the current time. Used to determine method to call at runtiime.


9.3 Overriding

overriding - A subclass method of the same name as a super class method will be called for the subclass object. The sub class method has precedence over the super class method.

In the following, the print() methods of CD and Video override the print() method of Item for CD and Item objects.

Item Video CD
public class Item
{
 private String title;
 private int playingTime;
 private boolean gotIt;
 private String comment;

 public void print()
 {
   System.out.print("title: " + title +
           " (" + playingTime + " mins)");
   if(gotIt) {
      System.out.println("*");
   } else {
     System.out.println();
   }
   System.out.println(" " + comment);
 }

public class Video extends Item
{
  private String director;

 


 public void print()
 {
    System.out.println("Video " +
               director);
 }

:
:

public class CD extends Item
{
  private String artist;
  private int numberOfTracks;



  public void print()
  {
    System.out.println("CD " + artist);
    System.out.println(" tracks: " +
                         numberOfTracks);
  }

:
:


9.4 Dynamic method lookup

method lookup - How methods are called. 

v1.print();

  1. v1 accessed.
  2. v1 found to be a Video object.
  3. Video class has a print() method.
  4. Video print() executed.

 

v1.print();

  1. v1 accessed.
  2. v1 found to be a Video object.
  3. Video class has a print() method.
  4. Video print() executed. Item print() blocked.

 

 

v1.print();

  1. v1 accessed.
  2. v1 found to be a Video object.
  3. Video class has a print() method.
  4. Video print() executed. Item print() blocked.


9.5 Super call in methods

In the following, the print() methods of CD and Video override the print() method of Item for CD and Item objects.

To call the print() method of Item for CD and Item objects, the print() methods call super class print() method, Item.

No changes to super class method.

Item Video CD
public class Item
{
 private String title;
 private int playingTime;
 private boolean gotIt;
 private String comment;

 public void print()
 {
   System.out.print("title: " + title +
            " (" + playingTime + " mins)");
   if(gotIt) {
      System.out.println("*");
   } else {
     System.out.println();
   }
   System.out.println(" " + comment);
}

public class Video extends Item
{
  private String director;

 


  public void print()
 {
     super.print();
    System.out.println("Video " +
                director);
 }

:
:

public class CD extends Item
{
 private String artist;
 private int numberOfTracks;



 public void print()
 {
    super.print();
   System.out.println("CD " + artist);
   System.out.println(" tracks: " +
                        numberOfTracks);
 }

:
:

Exercise 2 - Super call in methods

In BlueJ

  • Open chapter08/dome-v2
  • Add super.print() methods to CD and Video method print().
  • Create a Video, CD and Database object.
    • Use Database method addItem() to add the CD and Video object to the database.
  • Call the Database method list() to print the database.
    • Did the Item, CD and Video method print() execute?


9.10 Summary