Inheritance

Polymorphism

Both Class & Interface Inheritance facilitate polymorphism!

  • Class Inheritance: Subclasses can override parent methods, providing specialised behaviour
  • Interface Implementation: Different classes implement the same interface contract differently

Both allow collections of mixed types to be processed uniformly.

  • Class: A variable of type Animal can store a Dog, Cat, or Bird object
  • Interface: A variable of type List can store an ArrayList or LinkedList

Class vs Interface

Use Interfaces when the relationship is “has-a/can-do”, use Classes when the relationship is “is-a”.

Favor Interfaces When:

  • Relationship is “has-a/can-do”
  • Multiple inheritance is needed
  • Defining behavioural contracts without implementation details
  • Objects share capabilities but not identity (e.g. Comparable, Serializable)

Use Classes When:

  • Clear hierarchical “is-a” relationship exists
  • Shared implementation reduces code duplication
  • Objects share both behavioir and state
  • Natural inheritance chain is obvious (e.g., Animal → Dog)

Prefer Composition Over Inheritance:

  • Prefer “has-a/can-do” relationships (Interfaces) when hierarchy isn’t clear
  • More flexible than rigid inheritance chains
  • Easier to test and modify