SyntaxPilot
Courses/Low-Level Design/Lesson 8

Low-Level Design · Lesson 8 of 90 · 13 min

OOP 3: inheritance done right

inheritanceis-a relationshipextendssuperclasssubclasssupermethod overriding@Overrideconstructor chainingprotected membersfragile base class problemfinal classes and methodssealed classespermits

These are the notes for Low-Level Design (LLD) episode 8, the third pillar of object-oriented programming. We build a ride-hailing app with bikes, autos and cabs and learn both how to use inheritance and where it bites: inheritance and the is-a test, extends, superclass and subclass, super and constructor chaining, method overriding and @Override, protected members, the fragile base class problem, final classes and methods, sealed classes with permits, and multiple inheritance of type vs implementation with the diamond problem. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.

1. The problem: copy-paste classes

Three vehicle types, three classes written separately. The business adds a rule: 10% off rides over 10 km. It is added to Bike and Auto, and forgotten in Cab.

class Bike {
    String driver;
    Bike(String driver) { this.driver = driver; }
    int fare(int km) {
        int total = 20 + km * 8;
        if (km > 10) total = total * 90 / 100;   // long-ride discount
        return total;
    }
}
class Auto {
    String driver;
    Auto(String driver) { this.driver = driver; }
    int fare(int km) {
        int total = 30 + km * 12;
        if (km > 10) total = total * 90 / 100;   // long-ride discount
        return total;
    }
}
class Cab {
    String driver;
    Cab(String driver) { this.driver = driver; }
    int fare(int km) { return 50 + km * 18; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Bike 20 km: Rs " + new Bike("Ravi").fare(20));
        System.out.println("Auto 20 km: Rs " + new Auto("Sunil").fare(20));
        System.out.println("Cab  20 km: Rs " + new Cab("Anita").fare(20));
    }
}
Bike 20 km: Rs 162
Auto 20 km: Rs 243
Cab  20 km: Rs 410

The cab ride should cost Rs 369 after the discount; it charged Rs 410, with no error. The three classes share one idea (a vehicle with a driver and a fare by distance) but the code doesn't say so, so the shared rule has three homes and three chances to be forgotten. This is the DRY problem (Don't Repeat Yourself, episode 17).

2. Inheritance, extends, superclass and subclass

On the ride app In Java
Every vehicle has a driver and a fare per km Superclass Vehicle: the shared fields and methods
A bike is a vehicle, plus its own rates class Bike extends Vehicle: a subclass
A driver is not a vehicle; a cab has a driver The is-a test
  • Inheritance: a class gets (inherits) the fields and methods of another class and can add or change behaviour.
  • extends: the keyword that sets this up: class Bike extends Vehicle.
  • Superclass (also parent or base class): the class being extended (Vehicle).
  • Subclass (also child or derived class): the class that extends (Bike).
  • Every Java class without extends silently extends java.lang.Object, which is why every object has toString(), equals() and hashCode().
class Vehicle {
    protected final String driver;
    private final int base, perKm;
    Vehicle(String driver, int base, int perKm) {
        this.driver = driver; this.base = base; this.perKm = perKm;
    }
    int fare(int km) {
        int total = base + km * perKm;
        if (km > 10) total = total * 90 / 100;   // long-ride discount
        return total;
    }
}
class Bike extends Vehicle {
    Bike(String driver) { super(driver, 20, 8); }
}
class Auto extends Vehicle {
    Auto(String driver) { super(driver, 30, 12); }
}
class Cab extends Vehicle {
    Cab(String driver) { super(driver, 50, 18); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Bike 20 km: Rs " + new Bike("Ravi").fare(20));
        System.out.println("Auto 20 km: Rs " + new Auto("Sunil").fare(20));
        System.out.println("Cab  20 km: Rs " + new Cab("Anita").fare(20));
    }
}
Bike 20 km: Rs 162
Auto 20 km: Rs 243
Cab  20 km: Rs 369

The discount rule now has one home, so every vehicle gets every fix: the cab is discounted to Rs 369. super(...) (section 3) passes each vehicle's rates up to Vehicle.

The is-a test

Before you write extends, say the sentence: "X is a Y". Inherit only if it's true in the real world and stays true for every operation of Y.

Sentence True? Design
A cab is a vehicle Yes class Cab extends Vehicle
A driver is a vehicle No: a cab has a driver a field Driver driver;
An engine is a car No: a car has an engine a field Engine engine;
A garage is an ArrayList<Car> No: a garage holds cars a private List<Car> field

A has-a relationship (one object contains or uses another) is modelled with a field, not with inheritance. Extending ArrayList for a garage would expose every list method (clear(), remove(0)) to anyone using the garage.

3. super and constructor chaining

super means "my superclass". super(...) calls a superclass constructor; super.method() calls the superclass's version of a method.

class Vehicle {
    protected final String driver;
    Vehicle(String driver) {
        this.driver = driver;
        System.out.println("1. Vehicle part built for " + driver);
    }
}
class Cab extends Vehicle {
    Cab(String driver) {
        System.out.println("2. Cab part ready");
    }
}
public class Main {
    public static void main(String[] args) {
        Cab c = new Cab("Anita");
        System.out.println("Driver: " + c.driver);
    }
}
Main.java:9: error: constructor Vehicle in class Vehicle cannot be applied to given types;
    Cab(String driver) {
                       ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
1 error

The rule: every constructor first calls a superclass constructor. If you don't write super(...) as the first statement, the compiler inserts super() with no arguments. Vehicle has no no-argument constructor, so it fails: required: String, found: no arguments.

class Vehicle {
    protected final String driver;
    Vehicle(String driver) {
        this.driver = driver;
        System.out.println("1. Vehicle part built for " + driver);
    }
}
class Cab extends Vehicle {
    Cab(String driver) {
        super(driver);
        System.out.println("2. Cab part ready");
    }
}
public class Main {
    public static void main(String[] args) {
        Cab c = new Cab("Anita");
        System.out.println("Driver: " + c.driver);
    }
}
1. Vehicle part built for Anita
2. Cab part ready
Driver: Anita

The parent part of the object is always built first, then the child part. This chain of constructor calls up to Object is constructor chaining. super(...) must be the first statement in the constructor.

4. Method overriding and @Override

Autos have a minimum fare of Rs 50. Auto needs a different answer to the same question "what's the fare?". Writing a method in a subclass with the same name and parameter types as a superclass method, to replace it, is method overriding.

A typo makes it a different method, silently:

class Vehicle {
    private final int base, perKm;
    Vehicle(int base, int perKm) { this.base = base; this.perKm = perKm; }
    int fare(int km) { return base + km * perKm; }
}
class Auto extends Vehicle {
    Auto() { super(30, 12); }
    int Fare(int km) {
        return Math.max(50, super.fare(km));   // minimum fare Rs 50
    }
}
public class Main {
    public static void main(String[] args) {
        Vehicle ride = new Auto();
        System.out.println("Auto 1 km: Rs " + ride.fare(1));
    }
}
Auto 1 km: Rs 42

Fare (capital F) is a brand-new method; fare was never overridden, so the parent's version ran (Rs 42). An annotation is a label for the compiler that starts with @. @Override says "I mean to override a method from above":

class Vehicle {
    private final int base, perKm;
    Vehicle(int base, int perKm) { this.base = base; this.perKm = perKm; }
    int fare(int km) { return base + km * perKm; }
}
class Auto extends Vehicle {
    Auto() { super(30, 12); }
    @Override
    int Fare(int km) {
        return Math.max(50, super.fare(km));   // minimum fare Rs 50
    }
}
public class Main {
    public static void main(String[] args) {
        Vehicle ride = new Auto();
        System.out.println("Auto 1 km: Rs " + ride.fare(1));
    }
}
Main.java:8: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

A supertype is any superclass or interface above this class. Fix the name:

class Vehicle {
    private final int base, perKm;
    Vehicle(int base, int perKm) { this.base = base; this.perKm = perKm; }
    int fare(int km) { return base + km * perKm; }
}
class Auto extends Vehicle {
    Auto() { super(30, 12); }
    @Override
    int fare(int km) {
        return Math.max(50, super.fare(km));   // minimum fare Rs 50
    }
}
public class Main {
    public static void main(String[] args) {
        Vehicle ride = new Auto();
        System.out.println("Auto 1 km: Rs " + ride.fare(1));
    }
}
Auto 1 km: Rs 50

super.fare(km) reuses the parent's calculation inside the override. Rules for a valid override:

  • same name and same parameter types (the return type may be a subclass type: covariant return, episode 9);
  • access can't be weaker (a public method can't be overridden as private);
  • static, private and final methods can't be overridden;
  • always write @Override.

5. protected members

Modifier Who can use it
private Only the same class (subclasses inherit the field but can't touch it)
(none) package-private Classes in the same package
protected Subclasses, plus classes in the same package
public Everyone

A package is a named folder of related classes (com.rideapp.vehicles).

class Vehicle {
    private int base = 20;
}
class Cab extends Vehicle {
    int fare() { return base + 10; }
}
public class Main {
    public static void main(String[] args) { System.out.println(new Cab().fare()); }
}

Output:

Main.java:5: error: base has private access in Vehicle
    int fare() { return base + 10; }
                        ^
1 error

protected fields are risky: every subclass can read and write them, so the parent can never change them without breaking children, and any subclass can break the parent's invariants (episode 6). Prefer private fields + protected methods (hooks) when subclasses need access.

6. The fragile base class problem

import java.util.*;

class RideLog {
    private final List<String> rides = new ArrayList<>();
    void add(String ride) { rides.add(ride); }
    void addAll(List<String> list) {
        for (String r : list) add(r);
    }
}
class CountingLog extends RideLog {
    int count = 0;
    @Override void add(String ride) { count++; super.add(ride); }
    @Override void addAll(List<String> list) {
        count += list.size();
        super.addAll(list);
    }
}
public class Main {
    public static void main(String[] args) {
        CountingLog log = new CountingLog();
        log.addAll(List.of("Ravi", "Sunil", "Anita"));
        System.out.println("Rides counted: " + log.count);
    }
}
Rides counted: 6

Three rides, counted six times. RideLog.addAll calls add internally (a hidden detail, never a promise). CountingLog overrides both: addAll counts 3, then the parent's addAll calls the overridden add three more times. And if the author of RideLog later rewrites addAll without calling add, the count changes again, though CountingLog never changed.

The fragile base class problem: harmless-looking changes (or hidden internal details) in a superclass break its subclasses. The root cause: inheritance breaks encapsulation; a subclass depends on how its parent's methods call each other, not just on what they promise. The same trap exists in the JDK: extending HashSet and overriding both add and addAll double-counts in the same way.

Defences:

  1. Design for inheritance or forbid it: if a class isn't designed and documented for extension, make it final.
  2. Make methods subclasses must not change final.
  3. Prefer composition (hold a RideLog as a field and forward calls), episode 11.

7. final classes and methods

import java.util.*;

final class RideLog {
    private final List<String> rides = new ArrayList<>();
    void add(String ride) { rides.add(ride); }
    void addAll(List<String> list) {
        for (String r : list) add(r);
    }
}
class CountingLog extends RideLog {
    int count = 0;
    @Override void add(String ride) { count++; super.add(ride); }
    @Override void addAll(List<String> list) {
        count += list.size();
        super.addAll(list);
    }
}
public class Main {
    public static void main(String[] args) {
        CountingLog log = new CountingLog();
        log.addAll(List.of("Ravi", "Sunil", "Anita"));
        System.out.println("Rides counted: " + log.count);
    }
}
Main.java:10: error: cannot inherit from final RideLog
class CountingLog extends RideLog {
                          ^
1 error
class Vehicle {
    final int fare(int km) { return 20 + 8 * km; }
}
class Auto extends Vehicle {
    int fare(int km) { return 50; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Auto().fare(2));
    }
}

Output:

Main.java:5: error: fare(int) in Auto cannot override fare(int) in Vehicle
    int fare(int km) { return 50; }
        ^
  overridden method is final
1 error
  • A final class can't be extended. String, Integer and records are final, so nobody can create a sneaky String subclass that changes its value.
  • A final method is inherited but can't be overridden; use it for steps every subclass must keep (the Template Method pattern, episode 38).

8. Sealed classes and permits

final is all or nothing. A sealed class names exactly which classes may extend it, with the permits keyword, like a wedding guest list. Sealed classes became a permanent Java feature in Java 17 (JEP 409).

sealed abstract class Vehicle permits Bike, Auto, Cab {
    abstract int fare(int km);
}
final class Bike extends Vehicle {
    int fare(int km) { return 20 + km * 8; }
}
final class Auto extends Vehicle {
    int fare(int km) { return 30 + km * 12; }
}
non-sealed class Cab extends Vehicle {
    int fare(int km) { return 50 + km * 18; }
}
class Truck extends Vehicle {
    int fare(int km) { return 0; }
}
public class Main {
    public static void main(String[] args) {
        Vehicle v = new Cab();
        System.out.println("Cab 5 km: Rs " + v.fare(5));
    }
}
Main.java:13: error: class is not allowed to extend sealed class: Vehicle (as it is not listed in its 'permits' clause)
class Truck extends Vehicle {
^
1 error

Each permitted subclass must choose one of three modifiers:

Modifier Meaning
final No further subclasses
sealed Its own permits list
non-sealed Open again: anyone may extend it

Leaving it out is a compile error:

sealed abstract class Vehicle permits Bike, Auto {
    abstract int fare(int km);
}
final class Bike extends Vehicle { int fare(int km) { return 20 + 8 * km; } }
class Auto extends Vehicle { int fare(int km) { return 30 + 12 * km; } }
public class Main {
    public static void main(String[] args) {
        System.out.println(new Auto().fare(2));
    }
}

Output:

Main.java:5: error: sealed, non-sealed or final modifiers expected
class Auto extends Vehicle { int fare(int km) { return 30 + 12 * km; } }
^
1 error

Fixed, with an open branch under Cab:

sealed abstract class Vehicle permits Bike, Auto, Cab {
    abstract int fare(int km);
}
final class Bike extends Vehicle {
    int fare(int km) { return 20 + km * 8; }
}
final class Auto extends Vehicle {
    int fare(int km) { return 30 + km * 12; }
}
non-sealed class Cab extends Vehicle {
    int fare(int km) { return 50 + km * 18; }
}
class LuxuryCab extends Cab {
    int fare(int km) { return 2 * super.fare(km); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Cab 5 km: Rs " + new Cab().fare(5));
        System.out.println("Luxury 5 km: Rs " + new LuxuryCab().fare(5));
    }
}
Cab 5 km: Rs 140
Luxury 5 km: Rs 280

Why seal? It documents "these are all the kinds there are", it stops outsiders from adding kinds you never planned for, and it lets the compiler check that a switch handles every kind (episode 9).

9. Multiple inheritance and the diamond problem

class Car { void drive() { System.out.println("Driving"); } }
class Boat { void sail() { System.out.println("Sailing"); } }
class AmphiCar extends Car, Boat { }
public class Main {
    public static void main(String[] args) {
        new AmphiCar().drive();
    }
}
Main.java:3: error: '{' expected
class AmphiCar extends Car, Boat { }
                          ^
1 error

A Java class has exactly one superclass. Inheriting code from more than one class is multiple inheritance of implementation, and Java forbids it because of the diamond problem: if Car and Boat both extend Vehicle and each override start(), which start() does AmphiCar get? Drawn as a class diagram, the four classes form a diamond.

          Vehicle (start)
          /            \
   Car (start)      Boat (start)
          \            /
           AmphiCar  ->  start() = ?

Java's answer: one superclass, but many interfaces. A class can be many types (class AmphiCar extends Car implements Swimmer) while its code comes from one parent. That's multiple inheritance of type, and Java allows it.

Interfaces can have default methods (bodies, since Java 8), so the diamond can come back:

interface Electric {
    default String charge() { return "Charge: 2 hours"; }
}
interface FastCharge {
    default String charge() { return "Charge: 30 minutes"; }
}
class EvCab implements Electric, FastCharge { }
public class Main {
    public static void main(String[] args) {
        System.out.println(new EvCab().charge());
    }
}
Main.java:7: error: types Electric and FastCharge are incompatible;
class EvCab implements Electric, FastCharge { }
^
  class EvCab inherits unrelated defaults for charge() from types Electric and FastCharge
1 error

Java refuses to guess; you resolve it by overriding and choosing with Interface.super.method():

interface Electric {
    default String charge() { return "Charge: 2 hours"; }
}
interface FastCharge {
    default String charge() { return "Charge: 30 minutes"; }
}
class EvCab implements Electric, FastCharge {
    public String charge() { return FastCharge.super.charge(); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new EvCab().charge());
    }
}
Charge: 30 minutes

The class diagram

                 «sealed, abstract» Vehicle
                 # driver: String
                 - base, perKm: int
                 + fare(km): int
                ^          ^           ^
   «final» Bike   «final» Auto      «non-sealed» Cab
                  + fare(km) @Override        ^
                                          LuxuryCab
                                          + fare(km)

A solid line with a hollow triangle pointing to the parent means inheritance (extends). # protected, - private, + public.

Common mistakes

Mistake Exact message Why Fix
No super(...) when the parent needs arguments error: constructor Vehicle in class Vehicle cannot be applied to given types; required: String found: no arguments Java inserted super() super(driver); as the first line
A typo in an override, no @Override no error: Auto 1 km: Rs 42 A new method, not an override Always write @Override
@Override on a method that overrides nothing error: method does not override or implement a method from a supertype Name or parameters don't match Fix the signature
Using a parent's private field error: base has private access in Vehicle private is class-only A protected method, or pass values to super(...)
Overriding methods that call each other no error: Rides counted: 6 Fragile base class final class, or composition
Extending a final class error: cannot inherit from final RideLog final = no subclasses Composition
Overriding a final method error: fare(int) in Auto cannot override fare(int) in Vehicle overridden method is final final = can't override Use a hook method instead
Extending a sealed class without permission error: class is not allowed to extend sealed class: Vehicle (as it is not listed in its 'permits' clause) Not on the list Add it to permits, or extend a non-sealed branch
Permitted subclass without a modifier error: sealed, non-sealed or final modifiers expected Must say what comes next Add final, sealed or non-sealed
Two superclasses error: '{' expected One superclass only One class + interfaces
Two interfaces with the same default error: types Electric and FastCharge are incompatible; Diamond via defaults Override and call X.super.m()

Mini project

Model a food-delivery fleet: every delivery partner's vehicle has a registration number and a cost per km. Bicycles cost Rs 2/km, scooters Rs 4/km, EV scooters Rs 3/km with a Rs 10 minimum per trip. Requirements: the "cost must never be negative" check lives in one final method; only these three kinds may exist; print the cost of a 2 km and a 10 km trip for each.

Solution
sealed abstract class FleetVehicle permits Bicycle, Scooter, EvScooter {
    private final String regNo;
    FleetVehicle(String regNo) { this.regNo = regNo; }
    String regNo() { return regNo; }
    final int tripCost(int km) {
        if (km < 0) throw new IllegalArgumentException("Bad km: " + km);
        return cost(km);
    }
    protected abstract int cost(int km);
}
final class Bicycle extends FleetVehicle {
    Bicycle(String r) { super(r); }
    @Override protected int cost(int km) { return 2 * km; }
}
final class Scooter extends FleetVehicle {
    Scooter(String r) { super(r); }
    @Override protected int cost(int km) { return 4 * km; }
}
final class EvScooter extends FleetVehicle {
    EvScooter(String r) { super(r); }
    @Override protected int cost(int km) { return Math.max(10, 3 * km); }
}
public class Main {
    public static void main(String[] args) {
        FleetVehicle[] fleet = { new Bicycle("BC-1"), new Scooter("KA05-1"), new EvScooter("KA05-2") };
        for (FleetVehicle v : fleet)
            System.out.println(v.regNo() + ": 2 km Rs " + v.tripCost(2) + ", 10 km Rs " + v.tripCost(10));
    }
}

Output:

BC-1: 2 km Rs 4, 10 km Rs 20
KA05-1: 2 km Rs 8, 10 km Rs 40
KA05-2: 2 km Rs 10, 10 km Rs 30

The fleet is sealed, the check is in a final method, each subclass is final and overrides only cost with @Override.

Practice

  1. Is-a or has-a? (a) Manager and Employee, (b) Order and OrderItem, (c) SavingsAccount and Account, (d) Car and Wheel.
Solution

(a) is-a (if managers really are employees in every way), (b) has-a, (c) is-a, (d) has-a.

  1. What does this print, and why?
class A {
    A() { System.out.println("A"); }
}
class B extends A {
    B() { System.out.println("B"); }
}
class C extends B {
    C() { System.out.println("C"); }
}
public class Main {
    public static void main(String[] args) { new C(); }
}
Solution

A, B, C: constructor chaining builds the parent part first. Each constructor starts with an implicit super().

  1. class Stack extends ArrayList<Integer> with push and pop. What's wrong?
Solution

A stack is not a list: callers can still call add(0, x), remove(3) or clear() and break the last-in-first-out rule. Use a private ArrayDeque<Integer> field and expose only push, pop, peek (composition).

  1. Fix the diamond: interface Printer { default String name() { return "Printer"; } }, interface Scanner { default String name() { return "Scanner"; } }, class Copier implements Printer, Scanner {}.
Solution

Add public String name() { return Printer.super.name() + "+" + Scanner.super.name(); } to Copier.

  1. When would you choose sealed over final or a normal class?
Solution

When there is a fixed, known set of kinds (payment states, vehicle types in a closed system, shapes in a library) that should be extendable only by you, and you want the compiler to check switches over them.

Quick quiz

Which of these is a real is-a relationship?

  • class Driver extends Vehicle
  • class Cab extends Vehicle
  • class Garage extends ArrayList<Car>
  • class Engine extends Car
Answer

class Cab extends Vehicle. A driver and an engine are parts (has-a: use fields); a garage holds cars but isn't a list.

Interview questions

  1. What is inheritance? What are its benefits and costs? A subclass reuses and specialises a superclass. Benefits: reuse, one home for shared rules, polymorphism. Costs: tight coupling to the parent's internals (fragile base class), a fixed hierarchy, and leaking unwanted methods.
  2. What does super do? super(...) calls a superclass constructor (must be the first statement); super.m() calls the superclass's version of an overridden method.
  3. What is constructor chaining? Every constructor first calls a superclass constructor (explicitly or an implicit super()), up to Object, so parent parts are built first.
  4. Overriding vs overloading? Overriding: same signature in a subclass, chosen at run time. Overloading: same name, different parameters, chosen at compile time (episode 9).
  5. Why use @Override? The compiler verifies the method really overrides something, catching typos and signature mismatches.
  6. What is the fragile base class problem? Subclasses depending on the superclass's internal behaviour break when the superclass changes. Fix with final, documented hooks, or composition.
  7. What are sealed classes? Classes that restrict which classes may extend them via permits (Java 17); subclasses must be final, sealed or non-sealed.
  8. Why doesn't Java support multiple inheritance of classes? The diamond problem: ambiguous inherited implementations and state. Java allows multiple inheritance of type via interfaces, and forces you to resolve conflicting default methods.
  9. Can you override a static or private method? No. A static method with the same signature in a subclass hides the parent's; a private method isn't inherited, so a same-named method is unrelated.

Glossary

Term Meaning, with an example
Inheritance A class getting the fields and methods of another and specialising it. Bike inherits fare() from Vehicle
is-a relationship "X is a Y" is true, so X may extend Y. A cab is a vehicle
has-a relationship X contains or uses a Y, modelled as a field. A cab has a driver
extends Keyword making a class a subclass. class Bike extends Vehicle
Superclass (parent, base class) The class being extended. Vehicle
Subclass (child, derived class) The class that extends. Bike
Object The root class every Java class extends, directly or indirectly
super "My superclass": super(driver) calls its constructor, super.fare(km) its method
Constructor chaining Each constructor calling a superclass constructor first, up to Object. Prints "1. Vehicle" then "2. Cab"
Method overriding Redefining a superclass method with the same name and parameters in a subclass. Auto.fare with a minimum
Annotation A label for the compiler or tools, starting with @. @Override
@Override Annotation asking the compiler to check that a method overrides one from a supertype
Supertype Any superclass or interface above a class
Signature A method's name plus its parameter types. fare(int)
Package A named group (folder) of related classes. com.rideapp.vehicles
protected Visible to subclasses and the same package
Fragile base class problem Superclass changes or hidden details breaking subclasses. CountingLog counting 6
Composition Building a class by holding other objects as fields and forwarding calls (episode 11)
final class Can't be extended. final class RideLog, String
final method Can't be overridden. final int fare(int km)
Sealed class A class that lists, with permits, the only classes allowed to extend it (Java 17)
permits The list of allowed subclasses. sealed class Vehicle permits Bike, Auto, Cab
non-sealed Re-opens a permitted subclass to any extension. non-sealed class Cab
Multiple inheritance of implementation Inheriting code from more than one class; not allowed in Java
Multiple inheritance of type A class being many types through interfaces; allowed. class EvCab implements Electric, FastCharge
Diamond problem Ambiguity when a class inherits the same method from two parents that share an ancestor
Default method An interface method with a body (Java 8+). default String charge()
X.super.m() Calls interface X's default version of m. FastCharge.super.charge()

Summary

  • Inheritance (extends) gives shared rules one home; use it only when the is-a test passes, otherwise use a field (has-a).
  • Every constructor calls super(...) first: constructor chaining builds the parent part first.
  • Override with the same signature, and always write @Override.
  • Prefer private fields; protected fields couple children to the parent.
  • Fragile base class: subclasses see the parent's insides. Make classes final unless designed for extension; use sealed + permits for a closed family.
  • One superclass, many interfaces: Java has multiple inheritance of type, not of implementation; resolve diamond conflicts with X.super.m().

Next episode: OOP 4: polymorphism.