Unit 8 ยท Abstraction and polymorphism
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.
Printable and implement it for two unrelated classes.toString to produce useful diagnostic text.ArrayList<Payable>.implements promise?payment()?Mastery task: Model study resources with a common ProgressTrackable interface and calculate progress polymorphically.