- Prerequisites
- 6.1–6.3
- Covers
- IS-A relationship · Composition vs inheritance · Fragile base class problem · Liskov considerations
- Related
- 7.3 Composition · 7.4 Interface-Based Design · Book 5 Vol II (LSP, OCP) · Book 5 Vol III (Decorator)
On this page
1Concept / Definition
Inheritance design is the discipline of deciding when to use class inheritance and how to make it safe. The core question is whether a subclass is truly a behavioural subtype of its superclass — usable anywhere the superclass is, without surprises — and whether reuse could be achieved more safely by composition.
The guidance of the last thirty years is consistent: favour composition over inheritance, use inheritance for genuine, stable type families, and design and document for inheritance or else prohibit it (Joshua Bloch, Effective Java).
2Why It Exists
Inheritance couples a subclass to its superclass's implementation, not just its interface. The subclass depends on which methods call which, on protected state, and on behaviour that was never promised. When the superclass evolves, subclasses can break without any change of their own. These failures are hard to see in review and often appear only in production. Inheritance design exists to prevent them.
3Core Concepts
IS-A relationship
Inheritance should model an is-a relationship: a SavingsAccount is an Account. But the linguistic test is not enough. The real test is behavioural: can every piece of code written for Account work correctly with a SavingsAccount? The famous counter-example is Square extends Rectangle: mathematically a square is a rectangle, but a mutable Square cannot honour Rectangle's behaviour that width and height can be set independently.

class Rectangle {
protected int width, height;
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
int area() { return width * height; }
}
class Square extends Rectangle {
@Override void setWidth(int w) { width = height = w; }
@Override void setHeight(int h) { width = height = h; }
}
void resize(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
assert r.area() == 20; // fails for Square: area is 16
}Composition vs inheritance
Composition means a class holds a reference to another object and delegates to it: a Stack has a list, rather than is a list. Composition reuses implementation without creating a subtype relationship, exposes only the operations the class chooses, and lets the collaborator be replaced — even at run time, and in tests.

| Criterion | Inheritance | Composition |
|---|---|---|
| Relationship | is-a (subtype) | has-a / uses-a |
| Coupling | To superclass implementation, including protected members and self-calls | To the collaborator's public interface only |
| Exposed API | Everything inherited | Only what the class chooses to expose |
| Change at run time | No — fixed at compile time | Yes — inject a different collaborator |
| Testing | Needs the whole hierarchy | Collaborator can be faked |
| Multiple sources of reuse | One superclass only | Any number of collaborators |
Fragile base class problem
A base class is fragile when changes to its implementation — without changing its public signatures — break subclasses. The classic demonstration is a HashSet subclass that counts added elements by overriding both add and addAll. HashSet.addAll happens to call add for each element, so every element is counted twice. The subclass depended on an undocumented implementation detail.

public class CountingSet<E> extends HashSet<E> {
private int addCount;
@Override public boolean add(E e) { addCount++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c); // internally calls add() → double count
}
public int addCount() { return addCount; }
}
// Composition: a forwarding wrapper, independent of HashSet's internals
public class CountingSet2<E> implements Set<E> {
private final Set<E> delegate;
private int addCount;
public CountingSet2(Set<E> delegate) { this.delegate = delegate; }
@Override public boolean add(E e) { addCount++; return delegate.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return delegate.addAll(c); // delegate's internals cannot call back
}
// … remaining Set methods forward to delegate
}Liskov considerations
The Liskov Substitution Principle (Barbara Liskov, 1987) states that objects of a subtype must be usable wherever objects of the supertype are expected, without altering the correctness of the program. The compiler checks signatures; LSP is about behaviour.

Common LSP violations in real code: overriding a method to throw UnsupportedOperationException (the immutable views of List are a deliberate, documented exception), adding validation that rejects inputs the parent accepts, returning null where the parent never did, and ignoring state changes the parent guaranteed.
4How It Works Internally
Nothing in the JVM enforces good inheritance design; the risks are all at the source and design level. Java does offer tools to control inheritance: final classes and methods prevent extension or overriding; sealed classes and interfaces (Java 17) list exactly which classes may extend them, and each permitted subclass must itself be final, sealed or non-sealed. Sealed hierarchies give the compiler the complete set of subtypes, which enables exhaustive switches.

5APIs / Features / Syntax
Java gives a class designer precise control over how much extension a class allows. From none to the most:
| Tool | Effect | Use it for |
|---|---|---|
| final class (records and enums are implicitly final) | No subclasses at all | The default for concrete classes |
| Private or package-private constructors | No subclasses outside the class or package | Factories and internal hierarchies |
| sealed ... permits (Java 17) | Only the listed direct subclasses | Closed domain families with exhaustive switches |
| non-sealed | Reopens one branch of a sealed hierarchy | A deliberate extension point inside a closed family |
| final methods in an abstract class | The algorithm cannot be overridden | Template methods (Example 4) |
| protected abstract hooks | Subclasses must supply these steps, and only these | Designed extension points |
| @implSpec in Javadoc | Documents self-use: which methods call which | Every class meant for inheritance |
| A forwarding class | Reuse without depending on the wrapped class's internals | Decorators (Example 2) |

@implSpec is the tag the JDK itself uses for this. The Javadoc of AbstractCollection.addAll states in its @implSpec section that the implementation iterates over the argument and calls add for each element, which is exactly the self-use that breaks the counting subclass in section 3. A class that documents its self-use this way is designed for inheritance; one that does not should be final.
6Practical Examples
Example 1 — Replacing an inheritance hierarchy with composition
// Before: behaviour variations as subclasses — explodes combinatorially
class Notifier { void send(String msg) { … } }
class SmsNotifier extends Notifier { … }
class SmsAndEmailNotifier extends SmsNotifier { … }
class SlackAndSmsAndEmailNotifier extends SmsAndEmailNotifier { … }
// After: one interface, small implementations, composed at run time
interface Channel { void send(String msg); }
record CompositeChannel(List<Channel> channels) implements Channel {
public void send(String msg) { channels.forEach(ch -> ch.send(msg)); }
}
Channel alerts = new CompositeChannel(List.of(new SmsChannel(), new SlackChannel()));Example 2 — Mini program: the fragile base class, reproduced and fixed
Problem. Section 3 explains why a HashSet subclass that counts added elements counts some of them twice, and sketches the fix. This program runs the subclass next to a complete composition-based version: a reusable forwarding class plus a small decorator, applied to two different sets.
public class FragileBase {
@SuppressWarnings("serial")
static class InheritingCountingSet<E> extends HashSet<E> {
private int addCount;
@Override public boolean add(E e) { addCount++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c); // HashSet's addAll calls add() again
}
int addCount() { return addCount; }
}
// reusable forwarding class: every call goes to the wrapped set
static class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
ForwardingSet(Set<E> s) { this.s = s; }
public int size() { return s.size(); }
public boolean isEmpty() { return s.isEmpty(); }
public boolean contains(Object o) { return s.contains(o); }
public Iterator<E> iterator() { return s.iterator(); }
public Object[] toArray() { return s.toArray(); }
public <T> T[] toArray(T[] a) { return s.toArray(a); }
public boolean add(E e) { return s.add(e); }
public boolean remove(Object o) { return s.remove(o); }
public boolean containsAll(Collection<?> c) { return s.containsAll(c); }
public boolean addAll(Collection<? extends E> c) { return s.addAll(c); }
public boolean retainAll(Collection<?> c) { return s.retainAll(c); }
public boolean removeAll(Collection<?> c) { return s.removeAll(c); }
public void clear() { s.clear(); }
@Override public boolean equals(Object o) { return s.equals(o); }
@Override public int hashCode() { return s.hashCode(); }
@Override public String toString() { return s.toString(); }
}
static final class CountingSet<E> extends ForwardingSet<E> { // decorator
private int addCount;
CountingSet(Set<E> s) { super(s); }
@Override public boolean add(E e) { addCount++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c); // the wrapped set's add is not ours
}
int addCount() { return addCount; }
}
public static void main(String[] args) {
List<String> three = List.of("tea", "milk", "sugar");
InheritingCountingSet<String> inh = new InheritingCountingSet<>();
inh.addAll(three);
CountingSet<String> hash = new CountingSet<>(new HashSet<>());
hash.addAll(three);
CountingSet<String> tree = new CountingSet<>(new TreeSet<>()); // any Set
tree.addAll(three);
System.out.println("extends HashSet: " + inh.addCount() + " adds");
System.out.println("wraps a HashSet: " + hash.addCount() + " adds");
System.out.println("wraps a TreeSet: " + tree.addCount() + " adds, "
+ tree);
}
}extends HashSet: 6 adds
wraps a HashSet: 3 adds
wraps a TreeSet: 3 adds, [milk, sugar, tea]
Why it behaves this way. InheritingCountingSet.addAll adds 3, then super.addAll runs AbstractCollection.addAll, which calls add for each element, and because add is overridden those calls reach the counting override: 3 more. The decorator counts 3, because its addAll forwards to the wrapped set, and the wrapped set's internal calls to add go to its own method, not to CountingSet's (Figure 7). ForwardingSet is written once and reused by every decorator; as a bonus the counter now works with any Set, a TreeSet included. Guava's ForwardingSet and the JDK's Collections.unmodifiableSet follow the same idea.
Example 3 — Composition at run time: Example 1's channels, running
Problem. Example 1 replaces a subclass per combination with channels composed at run time. This program runs that design and adds one more behaviour, throttling, as a decorator rather than as yet another subclass.
public class Channels {
interface Channel { void send(String msg); }
record SmsChannel(List<String> log) implements Channel {
public void send(String msg) { log.add("sms: " + msg); }
}
record SlackChannel(List<String> log) implements Channel {
public void send(String msg) { log.add("slack: " + msg); }
}
record CompositeChannel(List<Channel> channels) implements Channel {
public void send(String msg) { channels.forEach(ch -> ch.send(msg)); }
}
record Throttled(Channel inner, int max, int[] sent) implements Channel {
public void send(String msg) { // a decorator
if (sent[0]++ < max) inner.send(msg);
}
}
public static void main(String[] args) {
List<String> log = new ArrayList<>();
Channel alerts = new CompositeChannel(List.of(
new SmsChannel(log),
new Throttled(new SlackChannel(log), 1, new int[1])));
alerts.send("disk 90%");
alerts.send("disk 95%");
log.forEach(System.out::println);
System.out.println(log.size() + " messages, no combined subclass");
}
}sms: disk 90%
slack: disk 90%
sms: disk 95%
3 messages, no combined subclassWhy it behaves this way. CompositeChannel is itself a Channel, so a group of channels can be used wherever one channel can. Throttled wraps any channel and decides whether to pass a message on; here it lets the first Slack message through and drops the second, while SMS receives both. Each behaviour is one small class, and a new combination is a new arrangement of objects, not a new class: with inheritance, SMS plus throttled Slack would already have needed its own subclass.
Example 4 — Designing a class for extension safely
public abstract class ImportJob {
/** Template method: the algorithm is fixed and cannot be overridden. */
public final ImportResult run(Path file) {
List<Record> records = parse(file);
List<Record> valid = records.stream().filter(this::isValid).toList();
return store(valid);
}
/** Hook: subclasses must parse the file format. Called once per run. */
protected abstract List<Record> parse(Path file);
/** Hook with a safe default. Must not have side effects. */
protected boolean isValid(Record r) { return true; }
private ImportResult store(List<Record> valid) { … } // not overridable
}Example 5 — Square and Rectangle: an LSP violation caught by a test
Problem. Section 3 shows why Square extends Rectangle breaks resize. A useful habit is to write the supertype's contract as one test and run it against every subtype; this program does that, then shows a design without the problem.
public class LspCheck {
static class Rectangle { // the box's version
protected int width, height;
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
int area() { return width * height; }
}
static class Square extends Rectangle {
@Override void setWidth(int w) { width = height = w; }
@Override void setHeight(int h) { width = height = h; }
}
// the supertype's contract as a test: width and height are independent
static String contractTest(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
return r.area() == 20 ? "PASS" : "FAIL (area " + r.area() + ")";
}
// the fix: immutable shapes, no setter to keep consistent
sealed interface Shape permits Rect, Sq {
int area();
}
record Rect(int width, int height) implements Shape {
public int area() { return width * height; }
Rect withWidth(int w) { return new Rect(w, height); }
}
record Sq(int side) implements Shape {
public int area() { return side * side; }
}
public static void main(String[] args) {
for (Rectangle r : List.of(new Rectangle(), new Square()))
System.out.println(r.getClass().getSimpleName() + " contract: "
+ contractTest(r));
List<Shape> shapes = List.of(new Rect(5, 4).withWidth(6), new Sq(4));
for (Shape s : shapes) System.out.println(s + " area " + s.area());
}
}Rectangle contract: PASS
Square contract: FAIL (area 16)
Rect[width=6, height=4] area 24
Sq[side=4] area 16Why it behaves this way. The test encodes what Rectangle promises: after setWidth(5) and setHeight(4) the area is 20. Square compiles as a subtype but cannot keep that promise, because its setters change both sides, so the same test fails for it with 16. The fix removes the promise that caused the conflict: immutable shapes have no setters, Rect.withWidth returns a new rectangle, and Sq is a separate type beside Rect rather than below it. Both satisfy everything Shape promises, which is only area().
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Inheriting to reuse code (a Stack that extends ArrayList; the JDK's own Stack extends Vector) | Unwanted operations exposed; LSP broken | Composition and delegation |
| Extending classes not designed for it | Fragile base class failures on upgrade | Wrap with composition (Decorator) |
| Subclass per feature combination | Class explosion | Composition, Strategy, Decorator |
| Overriding to throw UnsupportedOperationException | Polymorphic callers fail | Smaller interfaces (ISP), or don't inherit |
| Protected mutable state in base classes | Subclasses break invariants | Private state, protected methods |
| Open, undocumented hierarchies in shared libraries | Every change risks unknown subclasses | final by default; sealed for closed families |
| Leaving classes non-final "in case someone needs it" | Every public method becomes a promise to subclasses nobody has seen | final by default; open a class deliberately, with documented hooks |
| Public or overridable steps in a Template Method | Callers run the steps out of order, or subclasses replace the algorithm itself | Final template, protected hooks, private shared steps (Example 4) |
8Performance & Production Considerations
Composition adds one level of delegation, which the JIT inlines, so there is no meaningful performance difference between the two approaches. The production concern is stability: fragile hierarchies turn library upgrades into incidents. Libraries that avoid exposing extensible classes can evolve their internals freely.
9Architecture & Design Considerations

At architecture level the same trade-off appears between frameworks and libraries. A framework that requires you to extend its base classes couples your code to its implementation and makes upgrades harder; frameworks that rely on interfaces, annotations and composition (modern Spring, for example) are easier to evolve. When your team publishes shared libraries, prefer interfaces and final classes, and use sealed types for closed domain families.
10Interview Questions & Answers
What does "favour composition over inheritance" mean?
Prefer to reuse behaviour by holding and delegating to other objects (has-a) rather than extending classes (is-a), because composition couples only to public interfaces, exposes only chosen operations, and allows collaborators to change at run time.
What is the Liskov Substitution Principle?
Objects of a subtype must be substitutable for objects of their supertype without breaking the correctness of the program: subtypes must not strengthen preconditions, weaken postconditions, violate invariants or throw unexpected exceptions.
Why is Square extends Rectangle problematic?
A mutable Rectangle promises that width and height can be set independently. Square cannot keep that promise, so code that works for rectangles — set width 5, height 4, expect area 20 — fails for squares. It passes the is-a language test but fails behavioural substitutability.
What is the fragile base class problem?
Changes to a superclass's implementation, or dependence on its undocumented internal behaviour such as which methods call which, break subclasses even though no public signature changed. The HashSet addAll/add double-counting example is the standard illustration. Example 2 reproduces it: 6 adds counted for 3 elements.
How would you add counting behaviour to a Set without extending HashSet?
Write a class that implements Set, holds any Set as a delegate, counts in add and addAll, and forwards every call to the delegate — the Decorator pattern. It works with any Set implementation and is unaffected by the delegate's internal self-calls. Example 2 shows a complete version with a reusable forwarding class.
What do sealed classes add to inheritance design?
They restrict which classes may extend a type, making the hierarchy closed and known to the compiler. This prevents unintended subclasses, documents the complete set of variants, and enables exhaustive switch patterns without a default branch.
When is class inheritance a good choice?
For a small, stable family of genuine subtypes that satisfy LSP; for template-method style base classes designed and documented for extension; and for abstract convenience classes behind an interface. Ideally the family is sealed or the extension points are explicit.
How do you detect LSP violations in a codebase?
Look for overrides throwing UnsupportedOperationException, instanceof checks on subtypes in client code, subclasses adding stricter validation, and tests that pass for the base class but fail for subclasses. Contract tests run against every implementation make violations visible.
How does inheritance design affect library and framework evolution?
Every public non-final class and overridable method is a potential extension point that the library must keep stable, including internal self-calls. Libraries that expose interfaces and final classes can change implementations freely; those that expose extensible classes accumulate compatibility constraints and break users on upgrade.
A legacy system has a six-level class hierarchy for product types that no one dares to change. How would you approach it?
First add characterisation tests around current behaviour. Identify what really varies (pricing, tax, shipping rules) and extract each into a strategy interface composed into a flatter product model. Migrate subclass by subclass behind the existing API, and consider a sealed interface for the stable set of product kinds. Use the strangler approach rather than a big-bang rewrite.
What rules would you set for inheritance in a large organisation's Java codebase?
Final by default; inheritance only for designed extension points, documented with their hooks and self-use; interfaces for public extension; sealed types for closed domain families; composition and decorators for reuse; no protected mutable state; and architecture tests or static-analysis rules to flag new inheritance from framework or library classes that are not designed for it.
What does this program print?
public class StackQuiz {
public static void main(String[] args) {
Stack<String> s = new Stack<>();
s.push("a");
s.push("b");
s.add(0, "z"); // inherited from Vector
System.out.println(s.pop() + " " + s + " " + s.get(0));
}
}It prints b [z, a] z. java.util.Stack extends Vector, so it inherits every list operation, including add(0, "z"), which inserts at the bottom of the stack, something no stack should allow. pop() still takes "b" from the top, leaving [z, a], and get(0) reads the bottom element directly. This is the classic case of inheriting to reuse code: use ArrayDeque through the Deque interface instead.
How does the JVM enforce a sealed hierarchy?
javac writes a PermittedSubclasses attribute into the sealed class file, and checks that every listed class extends it directly and is declared final, sealed or non-sealed. The JVM checks the attribute again when it loads a subclass: a class that names a sealed superclass without being listed fails with IncompatibleClassChangeError, so the restriction holds even for bytecode compiled separately or generated at run time. Permitted subclasses must be in the same module, or in the same package if the code is not in a named module.
Records cannot extend other classes. How do you share behaviour between records, and is the restriction a problem?
Records can implement interfaces, so shared behaviour goes into default methods on a common interface, often a sealed one, and shared data into a small record used as a component, which is composition. A record extending a class would lose the guarantee that its state is exactly its components, which is what makes the generated equals, hashCode and deconstruction patterns correct. The restriction is rarely a problem in practice; when it is, the type is probably not a pure data carrier and should be an ordinary final class.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Inheritance is justified only for behavioural subtypes — LSP, not just the is-a wording.
- Composition reuses code with less coupling and more flexibility.
- Fragile base classes break subclasses through internal changes; wrap instead of extending.
- Design for inheritance explicitly (final template, documented hooks) or prohibit it.
- Sealed types give controlled, closed hierarchies with compiler support.