These are the notes for Low-Level Design (LLD) episode 11. "Favour composition over inheritance" may be the most quoted piece of design advice there is. Last episode we met composition: an object built from parts it owns. Today we put it against inheritance (extends, episode 8), watch inheritance break three different ways, and learn when it is still the right tool: composition over inheritance, forwarding, delegation, has-a vs is-a, the class explosion problem, behaviour injection, mixin-style default methods, when inheritance is the right choice, and refactoring inheritance to composition. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The problem: a registration counter that counts wrong
The college fest needs a registration counter: how many names were ever added. The obvious way: reuse Java's HashSet (episode 4), a collection that stores unique items (adding the same name twice keeps one copy). Extend it and override its add methods to count.
Quick reminders:
class A extends B(inheritance): A gets all of B's fields and methods and can be used wherever a B is expected.- Overriding (
@Override): a subclass redefines a method it inherited, with the same name and parameters. super.add(s)calls the parent's version ofadd.Collection<? extends String>means "any collection (list, set...) whose items areStringor a subtype of it". The?is a wildcard: an unknown type, limited byextends String.
import java.util.*;
class CountingSet extends HashSet<String> {
int added = 0;
@Override public boolean add(String s) {
added++;
return super.add(s);
}
@Override public boolean addAll(Collection<? extends String> c) {
added += c.size();
return super.addAll(c);
}
}
public class Main {
public static void main(String[] args) {
CountingSet reg = new CountingSet();
reg.addAll(List.of("Ravi", "Meena", "Arjun"));
System.out.println("Registered: " + reg.added);
}
}
Registered: 6
Three students, counted six times. No error.
What went wrong
Follow the call:
our addAll(3 names) -> added += 3 (count: 3)
super.addAll(...) -> HashSet's addAll calls add() once per name
our add("Ravi") -> added++ (count: 4)
our add("Meena") -> added++ (count: 5)
our add("Arjun") -> added++ (count: 6)
Inside HashSet, addAll does its job by calling add once per item, and add is now our override, which counts again. A class calling its own overridable methods is called self-use. It is an internal detail nobody promised you; it is not in the method's contract.
- The subclass broke because it depended on how the parent works inside. That is the fragile base class problem (episode 8): a change in, or a hidden habit of, the parent (base) class breaks its subclasses.
- Inheritance breaks encapsulation (episode 6): the subclass sees the parent's implementation, not just its public interface.
- A future Java version could change HashSet's insides and break us in a new way.
The fix: don't BE a HashSet. HAVE one.
2. Composition and forwarding
import java.util.*;
class CountingSet {
private final Set<String> inner = new HashSet<>(); // has-a
private int added = 0;
boolean add(String s) {
added++;
return inner.add(s); // forwarding
}
boolean addAll(Collection<String> c) {
added += c.size();
return inner.addAll(c); // forwarding
}
int added() { return added; }
}
public class Main {
public static void main(String[] args) {
CountingSet reg = new CountingSet();
reg.addAll(List.of("Ravi", "Meena", "Arjun"));
System.out.println("Registered: " + reg.added());
}
}
Registered: 3
CountingSetno longer extends anything. It has a privateHashSetfield calledinner. That's composition.- Its
addcounts, then passes the call straight toinner. Passing a call, unchanged, to the object you hold is called forwarding. The methods that do this are forwarding methods. - Now
inner.addAllcallsinner's ownadd, not ours. HashSet's private habits stay private.
3. Delegation
Delegation: handing a piece of work to another object instead of doing it yourself. Forwarding is its simplest form. Our counter delegates storage to the set and keeps only counting for itself.
| At a restaurant | In Java |
|---|---|
| You only talk to the waiter | CountingSet: the object callers use |
| He passes your order to the chef, unchanged | Forwarding: inner.add(s) |
| He also writes the bill: his own small job | Delegation: keep your job, hand off the rest |
| The waiter isn't a chef; he has one | Has-a, not is-a |
(Strictly, some books use "delegation" only when the helper object also calls back into the original object. In everyday design talk, and in this course, delegation means "give the work to an object you hold".)
4. Has-a vs is-a: the undo history
Second trap: inheriting things you never wanted. A text editor's undo history is a stack: LIFO, "last in, first out", like a pile of plates: the last action pushed is the first one undone. UndoHistory extends ArrayList and adds push (add at the end) and pop (remove the last).
import java.util.*;
class UndoHistory extends ArrayList<String> { // is-a list?
void push(String action) { add(action); }
String pop() { return remove(size() - 1); }
}
public class Main {
public static void main(String[] args) {
UndoHistory h = new UndoHistory();
h.push("type A");
h.push("type B");
h.push("bold");
h.sort(null); // someone sorts it to show it A to Z
System.out.println("Undo: " + h.pop());
}
}
Undo: type B
The last action was bold, but type B was undone. sort(null) sorts the list in natural (alphabetical) order, so the order of actions was lost. It was legal because UndoHistory is an ArrayList: it inherited dozens of public methods (sort, insert in the middle, clear...), all able to break the stack's one rule, LIFO.
Ask the is-a question honestly: is an undo history a list, usable anywhere a list is? No. It has a list. So: composition. Deque (episode 4, "double-ended queue") is an interface for a collection you can add to and remove from at both ends; ArrayDeque is its fast array-based implementation, and its push/pop work like a stack.
import java.util.*;
class UndoHistory {
private final Deque<String> items = new ArrayDeque<>(); // has-a
void push(String action) { items.push(action); }
String pop() { return items.pop(); }
}
public class Main {
public static void main(String[] args) {
UndoHistory h = new UndoHistory();
h.push("type A");
h.push("type B");
h.push("bold");
h.sort(null); // someone sorts it to show it A to Z
System.out.println("Undo: " + h.pop());
}
}
Main.java:13: error: cannot find symbol
h.sort(null); // someone sorts it to show it A to Z
^
symbol: method sort(<null>)
location: variable h of type UndoHistory
1 error
Now the compiler protects the rule: nobody can sort the history. Remove that line:
import java.util.*;
class UndoHistory {
private final Deque<String> items = new ArrayDeque<>(); // has-a
void push(String action) { items.push(action); }
String pop() { return items.pop(); }
}
public class Main {
public static void main(String[] args) {
UndoHistory h = new UndoHistory();
h.push("type A");
h.push("type B");
h.push("bold");
System.out.println("Undo: " + h.pop());
}
}
Undo: bold
Fun fact: Java's own Stack class made this exact mistake. Ask the JDK with javap (a tool that prints a compiled class's declaration) and it says:
public class java.util.Stack<E> extends java.util.Vector<E>
Vector is another list, so a Stack lets you insert in the middle too. For a stack, use a Deque like ArrayDeque.
| Is-a (inheritance) | Has-a (composition) |
|---|---|
| "A Car is a Vehicle" | "A Car has an Engine" |
class Car extends Vehicle |
class Car { private final Engine engine; } |
| Inherits every public method of the parent, wanted or not | Exposes only the methods you choose to write |
| Fixed when the class is written | Parts can be swapped while the program runs |
| Usable anywhere the parent is expected | Not a substitute for the part |
Rule: not truly is-a? Then don't extend.
5. The class explosion problem
A chai stall writes every combination on its menu board: ginger chai with sugar, ginger without, masala with, masala without... Three flavours times two is six items. Add honey and jaggery as sweeteners and the board explodes. A sensible stall writes: "chai + choose your flavour + choose your sweetener". Parts you combine at order time.
When every combination of features needs its own subclass, the number of classes multiplies. That's the class explosion problem.
Our college reports can be exported as PDF, Excel or CSV and sent by Email, WhatsApp or SMS. With inheritance, every pair becomes a subclass:
PdfEmailReport PdfWhatsAppReport PdfSmsReport
ExcelEmailReport ExcelWhatsAppReport ExcelSmsReport
CsvEmailReport CsvWhatsAppReport CsvSmsReport
- 3 formats x 3 channels = 9 subclasses. Add one format: 12.
- Worse, an object's class is fixed for life, so a report can't switch from email to WhatsApp while the app runs.
- With composition, a report has an exporter and has a sender: 3 + 3 = 6 small classes, combined freely. Multiplication becomes addition.
6. Behaviour injection
Behaviour injection: handing an object the behaviour it should use from outside (through its constructor or a setter method), instead of hard-coding it inside. (This is the basic idea behind what is often called dependency injection.)
A functional interface is an interface with exactly one abstract method, so a lambda (episode 5) can implement it in one line: d -> d + ".pdf" means "given d, return d + ".pdf"".
interface Exporter { String export(String data); }
interface Sender { void send(String file); }
class Report {
private final Exporter exporter;
private Sender sender;
Report(Exporter e, Sender s) { exporter = e; sender = s; } // injected
void setSender(Sender s) { sender = s; }
void publish(String data) {
sender.send(exporter.export(data)); // delegation
}
}
public class Main {
public static void main(String[] args) {
Exporter pdf = d -> d + ".pdf", csv = d -> d + ".csv";
Sender email = f -> System.out.println("Email: " + f);
Sender whatsapp = f -> System.out.println("WhatsApp: " + f);
Report marks = new Report(pdf, email);
marks.publish("marks");
marks.setSender(whatsapp); // swapped while running
marks.publish("marks");
new Report(csv, whatsapp).publish("attendance");
}
}
Email: marks.pdf
WhatsApp: marks.pdf
WhatsApp: attendance.csv
- Two tiny interfaces: an
Exporterturns data into a file name, aSendersends a file. Reportholds one of each and receives them through its constructor: behaviour injection.publishjust delegates: export the data, send the file. Report doesn't know or care which format or channel.setSenderswaps the channel at run time: the samemarksobject now sends by WhatsApp. Every combination, no new classes.
| In the kitchen | In Java |
|---|---|
| One motor base does the spinning | Report: the stable core |
| Swap the jar: chutney, dry masala, juice | Injected behaviour: Exporter, Sender |
| No new mixer per recipe | setSender(...): change behaviour while running |
7. Mixin-style default methods
Sometimes you want the same small behaviour in unrelated classes, like logging. A default method (episode 3) is an interface method with a body: every implementing class gets it for free.
interface Loggable {
default void log(String msg) {
System.out.println("[" + getClass().getSimpleName() + "] " + msg);
}
}
interface Auditable {
String owner();
default String audit() { return "changed by " + owner(); }
}
class FeeDesk implements Loggable { }
class Report implements Loggable, Auditable {
public String owner() { return "Mrs Rao"; }
}
public class Main {
public static void main(String[] args) {
new FeeDesk().log("reminder sent");
Report r = new Report();
r.log(r.audit());
}
}
[FeeDesk] reminder sent
[Report] changed by Mrs Rao
getClass().getSimpleName() returns the name of the object's actual class, like "FeeDesk". Auditable needs one thing from the class (owner()) and builds an audit line from it. A class can implement many interfaces, so small behaviours are mixed into unrelated classes without a common parent. An interface used like this is called a mixin: a bundle of behaviour you mix in.
The limit: no state
Let Loggable count its logs with an int field:
interface Loggable {
int count = 0; // try to remember how many logs
default void log(String msg) {
count++;
System.out.println("[" + getClass().getSimpleName() + "] " + msg);
}
}
interface Auditable {
String owner();
default String audit() { return "changed by " + owner(); }
}
class FeeDesk implements Loggable { }
class Report implements Loggable, Auditable {
public String owner() { return "Mrs Rao"; }
}
public class Main {
public static void main(String[] args) {
new FeeDesk().log("reminder sent");
Report r = new Report();
r.log(r.audit());
}
}
Main.java:4: error: cannot assign a value to static final variable count
count++;
^
1 error
Every field in an interface is automatically static (one shared copy for the whole program, not one per object) and final (can't be changed): a constant. State means the data an object remembers between calls (like a counter). Default methods can add behaviour, never state. When you need state, use composition: hold a Logger object (Practice 5).
8. When inheritance IS the right choice
Inheritance isn't bad. "Favour" composition is a default, not a ban. Inheritance is right when:
| Use inheritance when | Example |
|---|---|
| There is a true is-a: the child works everywhere the parent does, with no surprises | Bike and Car are real Vehicles (episodes 8 and 9) |
| The parent was designed to be extended: abstract methods, documented hooks (methods meant to be overridden) | abstract class Vehicle { abstract int fee(int hours); } |
| You control both classes (same team or package), so the parent can't change under you | Your own Vehicle hierarchy |
| It's a closed family | sealed interface Vehicle permits Bike, Car, Truck (episodes 8, 9) |
If you're extending just to reuse some code, compose instead.
| Choose composition when | Choose inheritance when |
|---|---|
| You only need some of another class's behaviour | The child truly is a kind of the parent |
| You don't control the other class's insides (JDK, library) | The parent is designed and documented for extension |
| Features combine in many ways (class explosion) | The family is small, closed and stable |
| Behaviour must change at run time | Behaviour is fixed per type |
9. Refactoring inheritance to composition
Refactoring means changing the structure of code without changing its behaviour. We did this twice today (CountingSet, UndoHistory). The steps:
- Add a private field of the old parent type:
private final Set<String> inner = new HashSet<>(); - Forward only the methods callers really need (
add,addAll). - Delete
extends: every unwanted inherited method disappears (sort,clear...). - Callers need polymorphism (they used it as a
Set)? Extract an interface with the needed methods and implement it. - Compile, run, compare the output with the output before the change.
class CountingSet extends HashSet<String> -> class CountingSet { private final Set<String> inner; }
The class diagram
Today's report design:
Report
- exporter: Exporter
- sender: Sender
+ publish(data)
+ setSender(s: Sender)
| 1 | 1
v v
«interface» Exporter «interface» Sender
+ export(data): String + send(file)
^ (dashed, hollow triangle) ^ (dashed, hollow triangle)
| |
Pdf / Excel / Csv Email / WhatsApp / Sms
| Element | Meaning |
|---|---|
Report |
The stable core; it never changes when a format or channel is added |
| Report to Exporter, Report to Sender (solid lines, multiplicity 1) | Has-a: two associations to interfaces, the injected behaviours |
| Pdf / Excel / Csv to Exporter, Email / WhatsApp / Sms to Sender (dashed lines, hollow triangles) | Realization: 3 + 3 small classes |
| Total | 6 classes cover all 9 combinations, no explosion |
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
class CountingSet extends HashSet<String> |
no error: Registered: 6 |
Parent's addAll calls add (self-use) |
Hold a Set, forward to it |
class UndoHistory extends ArrayList<String> |
no error: Undo: type B |
Inherited sort() breaks LIFO |
private Deque + push/pop only |
PdfEmailReport, PdfSmsReport, ... |
no error: 9 classes, 12 after one new format | Class explosion | Inject an Exporter and a Sender |
interface Loggable { int count = 0; ... count++; } |
error: cannot assign a value to static final variable count |
Interface fields are static final |
State lives in a composed object |
| Calling a removed inherited method after refactoring | error: cannot find symbol / symbol: method sort(<null>) |
The class no longer is-a list | Good: the misuse is now impossible. Remove the call |
Mini project
Rewrite the chai menu (the video's homework): Chai has a Flavour and has a Sweetener. Base chai is Rs 15; ginger adds Rs 5, masala Rs 10; sugar adds Rs 0, jaggery Rs 5, "no sugar" Rs 0. Requirements: inject both through the constructor, let the customer change the sweetener after ordering, and print three orders. How many classes would inheritance need for these 2 flavours x 3 sweeteners?
Solution
interface Flavour { String label(); int price(); }
interface Sweetener { String label(); int price(); }
class Ginger implements Flavour {
public String label() { return "ginger"; }
public int price() { return 5; }
}
class Masala implements Flavour {
public String label() { return "masala"; }
public int price() { return 10; }
}
class Sugar implements Sweetener {
public String label() { return "sugar"; }
public int price() { return 0; }
}
class Jaggery implements Sweetener {
public String label() { return "jaggery"; }
public int price() { return 5; }
}
class NoSweetener implements Sweetener {
public String label() { return "no sugar"; }
public int price() { return 0; }
}
class Chai {
private final Flavour flavour; // has-a
private Sweetener sweetener; // has-a, can change
Chai(Flavour f, Sweetener s) { flavour = f; sweetener = s; } // behaviour injection
void setSweetener(Sweetener s) { sweetener = s; }
int price() { return 15 + flavour.price() + sweetener.price(); } // delegation
String describe() { return flavour.label() + " chai, " + sweetener.label() + ": Rs " + price(); }
}
public class Main {
public static void main(String[] args) {
Chai order = new Chai(new Ginger(), new Sugar());
System.out.println(order.describe());
order.setSweetener(new Jaggery()); // customer changes their mind
System.out.println(order.describe());
System.out.println(new Chai(new Masala(), new NoSweetener()).describe());
}
}
Output:
ginger chai, sugar: Rs 20
ginger chai, jaggery: Rs 25
masala chai, no sugar: Rs 25
Inheritance would need 2 x 3 = 6 subclasses (and couldn't change the sweetener of an existing order). Composition uses 2 + 3 = 5 small classes plus Chai, and adding a flavour is one new class.
Practice
- Refactor
class Car extends Engine(the homework) into composition. Car should offerstart()anddrive(), anddrive()starts the engine if needed.
Solution
A car is not an engine; it has one.
class Engine {
private boolean running;
void start() { running = true; System.out.println("Engine started"); }
boolean isRunning() { return running; }
}
class Car { // was: class Car extends Engine
private final Engine engine = new Engine(); // has-a (composition)
void start() { engine.start(); } // forwarding
void drive() {
if (!engine.isRunning()) start();
System.out.println("Car is moving");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}
Engine started
Car is moving
- Implement design B from the quiz: a
Robotthat has a list ofMoves and can learn a new move at run time.
Solution
import java.util.*;
interface Move { String perform(); }
class Robot {
private final String name;
private final List<Move> moves = new ArrayList<>();
Robot(String name) { this.name = name; }
void learn(Move m) { moves.add(m); } // new behaviour at run time
void show() {
for (Move m : moves) System.out.println(name + " " + m.perform());
}
}
public class Main {
public static void main(String[] args) {
Move walk = () -> "walks", swim = () -> "swims", fly = () -> "flies";
Robot r = new Robot("R2");
r.learn(walk);
r.learn(fly);
r.show();
r.learn(swim); // a new move, no new Robot subclass
System.out.println("-- after learning to swim --");
r.show();
}
}
R2 walks
R2 flies
-- after learning to swim --
R2 walks
R2 flies
R2 swims
() -> "walks" is a lambda with no parameters.
- Is-a or has-a? (a)
ManagerandEmployee(b)CarandEngine(c)StackandVector(d)SavingsAccountandAccount(e)ReportandPdfExporter.
Solution
(a) Is-a: a manager is an employee. (b) Has-a. (c) Has-a: a stack only needs list storage inside; the JDK's Stack extends Vector exposes unwanted list methods. (d) Is-a. (e) Has-a: the report uses an exporter, injected so it can be swapped.
- In section 1, suppose a future Java version rewrote
HashSet.addAllso it no longer callsadd. What would the inheritance version print, and what would the composition version print? What does this tell you?
Solution
The inheritance version would then print Registered: 3; it only works or fails depending on the parent's hidden insides. The composition version prints Registered: 3 either way, because it never overrides anything inside HashSet. Composition depends only on the public contract, so it can't be broken by the parent's private changes.
- Loggable couldn't count its logs. Write a
Loggerthat keeps the count, and give it toFeeDeskandReportby composition (one shared logger).
Solution
class Logger { // the state lives here
private int count = 0;
void log(String who, String msg) {
count++;
System.out.println("#" + count + " [" + who + "] " + msg);
}
}
class FeeDesk {
private final Logger logger; // has-a Logger
FeeDesk(Logger logger) { this.logger = logger; }
void remind() { logger.log("FeeDesk", "reminder sent"); }
}
class Report {
private final Logger logger;
Report(Logger logger) { this.logger = logger; }
void publish() { logger.log("Report", "published"); }
}
public class Main {
public static void main(String[] args) {
Logger shared = new Logger();
new FeeDesk(shared).remind();
new Report(shared).publish();
new FeeDesk(shared).remind();
}
}
#1 [FeeDesk] reminder sent
#2 [Report] published
#3 [FeeDesk] reminder sent
The logger is injected through the constructor, so all three objects share one counter (this shared logger is aggregation, from episode 10).
Quick quiz
// A Robot can walk, swim or fly, in any mix.
// New moves are added every month.
A) class SwimmingFlyingRobot extends FlyingRobot
B) class Robot { private List<Move> moves; }
Which design is better?
- A: one subclass per mix
- B: compose a list of moves
- Both are equally good
- Neither compiles
Answer
B. Moves combine freely and grow every month: that's the class explosion signal, and subclasses would multiply. Compose: Robot has a list of Move objects; each new move is one new class, and any robot can learn it at run time (Practice 2).
Interview questions
- What does "favour composition over inheritance" mean? Build behaviour by holding and delegating to other objects (has-a) rather than by extending classes (is-a), unless there is a true, designed is-a relationship.
- Why can inheritance break encapsulation? A subclass depends on the parent's implementation, such as self-use (
addAllcallingadd). Changes to the parent's insides can break subclasses: the fragile base class problem. - What is forwarding? Delegation? Forwarding: passing a call unchanged to a held object (
inner.add(s)). Delegation: handing work to another object you hold; forwarding is the simplest form. - Is-a vs has-a: how do you decide? Ask whether the child can be used everywhere the parent is, with no surprises. If not (an undo history isn't a general list), use has-a.
- What's wrong with
java.util.Stack? It extendsVector, so it inherits list operations like inserting in the middle that break LIFO. PreferDeque/ArrayDeque. - What is the class explosion problem? Creating a subclass for every combination of independent features, so the count multiplies (3 formats x 3 channels = 9). Composition makes it additive (3 + 3).
- What is behaviour injection? Passing the varying behaviour into an object (constructor or setter) instead of hard-coding or subclassing it; it can be swapped at run time.
- What are mixins in Java, and their limit? Interfaces with default methods that add small behaviours to unrelated classes. They can't hold per-object state, because interface fields are
public static final. - When is inheritance the right choice? True is-a, parent designed for extension, you control both classes, or a closed (sealed) family.
- How do you refactor inheritance to composition? Add a private field of the parent type, forward the needed methods, delete
extends, extract an interface if callers need polymorphism, and compare outputs before and after.
Glossary
| Term | Meaning, with an example |
|---|---|
Inheritance (extends) |
A class getting all fields and methods of a parent; an is-a link. class Car extends Vehicle |
| Composition | Building an object from parts it holds and owns. private final Set<String> inner |
| Composition over inheritance | Design advice: prefer has-a + delegation to extending, by default |
HashSet |
A collection of unique items |
| Overriding | Redefining an inherited method in a subclass. @Override public boolean add(...) |
super.method() |
Calls the parent's version of a method |
Wildcard (? extends String) |
A generic type meaning "some unknown subtype of String" |
| Self-use | A class calling its own overridable methods internally. HashSet.addAll calling add |
| Fragile base class problem | Hidden details or changes in a parent class breaking its subclasses |
| Encapsulation | Hiding an object's insides behind methods (episode 6) |
| Forwarding | Passing a call unchanged to an object you hold. return inner.add(s); |
| Forwarding method | A method whose job is to forward a call |
| Delegation | Handing work to another object you hold instead of doing it yourself |
| Has-a | One object holds another as a part. A car has an engine |
| Is-a | One type is a kind of another. A car is a vehicle |
| Stack / LIFO | A pile where the last item in is the first out. Undo history |
Deque / ArrayDeque |
A double-ended queue interface / its array implementation; push/pop act as a stack |
sort(null) |
Sorts a list in natural (for strings, alphabetical) order |
javap |
JDK tool that prints a compiled class's declaration |
Vector |
An old JDK list class; Stack extends it |
| Class explosion problem | One subclass per combination of features, so classes multiply. PdfEmailReport... |
| Behaviour injection | Passing in the behaviour an object should use, instead of hard-coding it. new Report(pdf, email) |
| Setter | A method that changes a field. setSender(s) |
| Run time | While the program is running (vs compile time, when it's being compiled) |
| Functional interface | An interface with one abstract method; a lambda can implement it. Exporter |
| Lambda | A tiny unnamed function. d -> d + ".pdf" |
| Default method | An interface method with a body. default void log(String msg) |
| Mixin | An interface whose default methods add a small behaviour to unrelated classes. Loggable |
| Mixin-style default methods | Using default methods to mix shared behaviour into classes with no common parent |
getClass().getSimpleName() |
The short name of an object's actual class. "FeeDesk" |
static |
Belongs to the class, one shared copy, not per object |
| Constant | A static final value that never changes |
| State | Data an object remembers between calls. A log counter |
| Hook | A method a parent class is designed to let subclasses override |
| When inheritance is the right choice | True is-a, parent designed for extension, you control both classes, or a closed family. Bike extends Vehicle |
| Sealed type | A class or interface that lists its only subtypes with permits |
| Polymorphism | One call behaving differently per object (episode 9) |
| Refactoring | Changing code's structure without changing its behaviour |
| Extract interface | A refactoring: create an interface from a class's methods so callers depend on it |
| Refactoring inheritance to composition | Field of parent type, forward needed methods, delete extends, compare output |
Summary
- Extending a class exposes you to its insides: self-use made
CountingSetcount 6 (the fragile base class problem). - Composition + forwarding: hold the object, pass calls on; its habits stay private. Delegation: hand work to an object you hold.
- Has-a vs is-a: if it isn't truly a kind of the parent, don't extend (
UndoHistory, and the JDK's ownStack extends Vector). - Class explosion: combinations multiply subclasses; composition makes them add.
- Behaviour injection: pass in what varies, swap it at run time.
- Mixins (default methods) add behaviour, not state: interface fields are
static final. - Inheritance is right for true, designed, controlled, closed is-a families. "Favour" means default, not ban.
- Refactor in steps: field, forward, delete
extends, extract interface, compare output.
Next episode: SOLID 1: The Single Responsibility Principle: responsibilities, reasons to change, actors and the god class.