Excellent picture of Inheritance Hierarchy

So why not use the Mega-Superclass Object as the type for all our references? Since it is the superclass of all objects we can assign any object to it. When v is defined as type Vehicle we can use any methods that are defined in Vehicle or its superclasses (in this case Object is the only superclass). This concept  is called polymorphism.

  1. v.setVisible(true);
  2. v.moveRelative(20, 30);
  3. v.setSize(50, 80);

(a) and (c) are valid because they are defined in Vehicle. (b) is invalid because moveRelative was only defined in SuperFerry. You can only use moveRelative if the variable is of type SuperFerry or a subclass (if any exist). All is not lost however. If you really want to use moveRelative you can do it by using casting. Here is code to do it:

SuperFerry sf = (SuperFerry)v

Even though it was stored as a Vehicle all the SuperFerry information still exists. We just have to promote it to a SuperFerry by using a cast. That was done by putting the type in brackets.