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

source: week 11 lecture notes

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

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:

Casting

Subtypes can be assigned to super types (but not visa-versa)

Casting should be used sparingly to avoid the possibility of run-time errors.