Card c; Birthday b; Valentine v; Holiday h c = new Valentine("Debby", 8); //OK b = new Valentine("Elroy", 3); //WRONG v = new Valentine("Fiona", 3); //OK h = new Birthday ("Greg", 35); //WRONG
Here is a picture of another hierarchy: There are no abstract classes in this hierarchy, so each class can be instantiated. As seen previously, the following is OK:
parentReferenceVariable = referenceToChild ;
A reference variable of a parent type can hold a reference to an object of one of its child types (or a reference to one of their child types, and so on.) However, the opposite direction
// don't do this childReferenceVariable = referenceToParent ;
can not be done. Here are some variables:
Rodent rod; Rat rat; Mouse mou;
Look at the table and decide if each section of code is correct or not.
code section OK or Not? code section OK or Not? rod = new Rat(); rod = new FieldMouse(); mou = new Rat(); mou = new Rodent(); rat = new Rodent(); rat = new LabRat(); rat = new FieldMouse(); rat = new Mouse();
There is still much more to learn about inheritance and polymorphism.