Inheritance, encapsulation and polymorphism: adding a new type without editing old code
Why adding one customer tier meant editing nine files: put behavior in the right type with polymorphism, guard invariants with encapsulation, prefer composition to inheritance, how overloading and overriding pick a method, and how to review a class hierarchy an AI wrote.
On this page
1. The problem
Transfer fees are computed with if (tier == STANDARD) ... else if (tier == PREMIUM) ... in 9 files. Adding a CORPORATE tier, the AI edits 8 files and reports done. The 9th, invoice export, falls into else and charges 0: 1,200 free transactions in a week.
2. Key idea
When behaviour by type lives outside the type, every new type means editing every branch. Put it inside the type and a new type is just a new class.
| Idea | What it does | In other languages |
|---|---|---|
| Polymorphism | one call, each type runs its own version | Go: implicit interfaces; Rust: traits |
| Encapsulation | the object guards its invariants, logic doesn't leak out | Go: lower-case fields |
| Inheritance | subclasses reuse parent code, an "is-a" relationship | Go and Rust have no class inheritance |
Inheritance is just one route to polymorphism, and the most tightly coupled: subclasses depend on the parent's implementation details (the fragile base class). Getters and setters for every field aren't encapsulation: encapsulation means putting behaviour in the object (tell, don't ask).
2.1 Which approach?
Order of preference: interface + composition → sealed + switch → extends an abstract class → extends a concrete class.
| Approach | Use when | Don't use when |
|---|---|---|
| Interface + one class per type | behaviour belongs to the type, the set is open (strategies, plugins) | there's only one implementation "for future extension" |
sealed + pattern switch |
the set is closed, the logic belongs to the handler (mapping to HTTP) | outsiders need to add types |
extends |
truly "is-a" and the subclass can replace the parent everywhere (Liskov) | just to reuse a few methods |
The declared type (left of =) decides which methods and overloads you can call; the actual type decides which override runs.
3. In Java
An interface for polymorphism, a record per type.
interface FeePolicy { BigDecimal feeFor(BigDecimal amount); }
record FlatFee(BigDecimal fee) implements FeePolicy {
public BigDecimal feeFor(BigDecimal amount) { return fee; }
}
record PercentFee(BigDecimal rate) implements FeePolicy {
public BigDecimal feeFor(BigDecimal amount) {
return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
}
}
class Account { // encapsulation: the invariant lives in one place
private BigDecimal balance = BigDecimal.ZERO;
void withdraw(BigDecimal amount) {
if (balance.compareTo(amount) < 0) throw new IllegalStateException("insufficient");
balance = balance.subtract(amount);
}
}
BigDecimal fee = policy.feeFor(amount); // a new fee type doesn't touch this lineOther languages: C# needs virtual/override because methods aren't virtual by default; TypeScript doesn't need implements.
Overloads, overrides, hidden fields and Liskov
- An override can't narrow access or throw broader checked exceptions;
privateandstaticmethods can't be overridden. - Overloads are chosen at compile time by the argument's declared type: with
print(Object)andprint(String), calling with anObjectvariable that holds a string runs theObjectversion. List<Integer>.remove(1)calls theremove(int index)overload and removes by position; to remove the value useremove(Integer.valueOf(1)).- Fields aren't polymorphic: a subclass field with the same name only hides the parent's;
Animal a = new Dog(); a.namereadsAnimal's field. - Liskov: a subclass must be usable wherever the parent is.
Square extends Rectanglebreaks whenRectanglehassetWidth: setting width 5 and height 4 on a square no longer gives area 20. Immutable records (no setters) make that relationship safe again. - A bad downcast throws
ClassCastExceptionat runtime; use the patternif (a instanceof Dog d)instead of a bare cast.
4. Working with AI
Hand to AI: turning if (type == ...) chains into an interface + one class per type, tests for each type.
Check in AI-written code:
- No
if/switchby type repeated across files; type-specific behaviour lives in the type. -
extendsonly when the subclass can replace the parent everywhere; composition for reuse. - No setters for every field; business methods guard invariants.
- No silent
defaultreturning a value for unknown types.
5. Exercises
Exercise 1: Review Square extends Rectangle
The AI wrote this, saying "a square is a rectangle, so inherit for reuse". Find the bug, name a test that proves it, fix it.
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 = w; height = w; }
@Override void setHeight(int h) { width = h; height = h; }
}Solution to Exercise 1
It violates Liskov: code using a Rectangle expects setWidth(5); setHeight(4) to give area 20; with a Square it gives 16. "A square is a rectangle" holds for properties, not for classes with state-changing behaviour.
Test: void resize(Rectangle r) { r.setWidth(5); r.setHeight(4); assertEquals(20, r.area()); } called with new Square(): fails.
Fix: drop the setters, use immutable records record Rect(int w, int h) and record Square(int side), both implementing sealed interface Shape { int area(); }. Resizing creates a new object.
Exercise 2: Choose an interface or sealed
Transfer fees have 4 tiers; soon partners will add their own tiers through plugins. The AI proposes sealed interface FeePolicy permits Standard, Premium, Vip, Corporate with a switch in the service. Choose, explain, and say when sealed is the better fit.
Solution to Exercise 2
Choose an open interface (not sealed), one class per tier with feeFor: partners add tiers without touching your code, and callers only know policy.feeFor(amount).
Sealed + switch is right when you own the set of types and the logic belongs to the handler rather than the type: for example mapping a PaymentResult to an HTTP status. Then adding a subtype is a compile error in every unhandled switch, which is exactly what you want.
Summary
- Put type-specific behaviour in the type, don't scatter
ifs by type. - Polymorphism: one call, each type runs its own version.
- Encapsulation is behaviour guarding invariants, not getters and setters for every field.
- Interfaces and composition first;
extendsonly when Liskov holds. - The declared type picks the overload; the actual type picks the override.
Read more: Part 4: Abstract classes and interfaces.
Practice interview questions on this topic
- What are the four pillars of OOP, and does Java support multiple inheritance?
- Overloading vs overriding: how does the JVM decide which method to call?
- What does "favor composition over inheritance" mean? Give an example of inheritance causing harm?
- What is Liskov Substitution? Why is Square extends Rectangle wrong, and what are other violations?
Comments
Community rules