Another Hierarchy

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

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

Another Hierarchy

hierarchy of rodents

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 sectionOK or Not?code sectionOK 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();

QUESTION 15:

There is still much more to learn about inheritance and polymorphism.