With Week 11 being the last week for new topics to be introduced, Judy presented a lecture on Inheritance. I had read and worked through some inheritance tutorials previously but did not really grasp it with good clarity. Judy’s lecture did clarify a great deal.
Key advantages to inheritance:
- Avoid code duplication
- Re-use
- Easier maintenance
- Easier extendability
Static and Dynamic types
Vehicle v1 = new Car();
Static type = vechicle, Dynamic type = Car
Overriding
If for example a print method needs to be different for each subclass (ie: print()) the method must be defined in the super class and in the subclasses. Henceforth when an object which is an extension of the super class has the print method called it will (depending on the Dynamic type) call the relevant sub method.
Polymorphism
for (Item item : items) { item.print(); }
In the example above, assuming item is the super class with sub classes of Disc and Tape, item will perform polymorphism depending on the Dynamic type of the particular item is is iterating through.
Subtyping
Objects of subtypes can be used wherever objects of supertypes are expected:
public void addItem(Item theItem) { ... } DVD dvd = new DVD(...); CD cd = new CD(...); database.addItem(dvd); database.addItem(cd);
Casting
Subtypes can be assigned to super types (but not visa-versa)
Item anItem; CD aCD = new CD(); anItem = aCD; // correct; aCD = anItem; compile error! Casting, by specifying the object type, fixes this: aCD = (CD) anITEM;
Casting should be used sparingly to avoid the possibility of run-time errors.