Tutorial 1: Inheritance, Overriding, and Interfaces

Unit 8 ยท Abstraction and polymorphism

Objectives

Inheritance can share a stable common contract, but it should represent a genuine substitutable relationship. Polymorphism lets code depend on an abstraction while the runtime selects the concrete implementation.

interface Payable { double payment(); }

class Invoice implements Payable {
    private final double amount;
    Invoice(double amount) { this.amount = amount; }
    public double payment() { return amount; }
}

Payable item = new Invoice(125.0);
System.out.println(item.payment());

The variable type controls which operations are visible; the object's runtime type controls an overridden implementation. Prefer composition or interfaces when inheritance would create a fragile hierarchy.

Practice

  1. Create Printable and implement it for two unrelated classes.
  2. Override toString to produce useful diagnostic text.
  3. Store different implementations in one ArrayList<Payable>.

Self-check

  1. What does implements promise?
  2. Why can an interface reference call payment()?
  3. What is the benefit of programming to an interface?

Mastery task: Model study resources with a common ProgressTrackable interface and calculate progress polymorphically.