SteelReed

Search

Search posts, questions…

1. Java Core

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.

17 Nov 20269 min readMid

–

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.

JAVA
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 line

Other 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; private and static methods can't be overridden.
  • Overloads are chosen at compile time by the argument's declared type: with print(Object) and print(String), calling with an Object variable that holds a string runs the Object version.
  • List<Integer>.remove(1) calls the remove(int index) overload and removes by position; to remove the value use remove(Integer.valueOf(1)).
  • Fields aren't polymorphic: a subclass field with the same name only hides the parent's; Animal a = new Dog(); a.name reads Animal's field.
  • Liskov: a subclass must be usable wherever the parent is. Square extends Rectangle breaks when Rectangle has setWidth: 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 ClassCastException at runtime; use the pattern if (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/switch by type repeated across files; type-specific behaviour lives in the type.
  • extends only when the subclass can replace the parent everywhere; composition for reuse.
  • No setters for every field; business methods guard invariants.
  • No silent default returning 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.

JAVA
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; extends only 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

All OOP & Design questions →

Loading comments…