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:
// OK parentReferenceVariable = referenceToChild ;
As is this:
// OK parentReferenceVariable = referenceToChildofChild ;
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 its further descandants.) However, the opposite direction does not work:
// don't do this childReferenceVariable = referenceToParent ;
Also, siblings are not descendants, so this does not work
// don't do this referenceVariable = referenceToSibling ;
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.