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

Answer:

Card card2 = new Holiday( "Bob" ) ; 
Card card3 = new Birthday( "Emily", 18 ) ;

Yes, both are correct, since Holiday is-a Card and Birthday is-a Card so references to those objects will fit into variables of type Card.


Using Parent Class Reference Variables

A reference variable of class "C" can be used with any object that is related by inheritance to class "C". For example, a Card reference variable card2 can hold a reference to a Holiday object, a Valentine object, or a Birthday object. Often at run time, a reference variable of a parent class type holds a reference to a child object.

Important:

When a method is invoked, it is the class of the object (not of the variable) that determines which method is run.

This is what you would expect. The method that is run is part of the object (at least conceptually). For example:

Card card = new Valentine( "Joe", 14 ) ;
card.greeting();

Card card2 = new Holiday( "Bob" ) ; 
card2.greeting();

Card card3 = new Birthday( "Emily", 12 ) ; 
card3.greeting();

This will run the greeting() method for a Valentine, then it will run the greeting() method for a Holiday, then it will run the greeting() method for a Birthday. The type of the object in each case determines which version of the method is run.


QUESTION 12:

(Thought Question: ) Do you think the following will work?

Card card = new Valentine( "Joe", 14 ) ;
card.greeting();

card = new Holiday( "Bob" ) ; 
card.greeting();

card = new Birthday( "Emily", 12 ) ; 
card.greeting();