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
.
A reference variable of a class C can be used for any
object that inherits from class C.
For example,
a Card
reference variable card2
can hold a reference to a Holiday
object,
a Valentine
object,
or a Birthday
object.
Of course, if the parent class is abstract,
then the variable can only point at class that inherits from the parent.
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. 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.
(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();