November 24, 20269 minutes
A subclass that refuses what it inherits still advertises it. Learn to spot Refused Bequest, why it breaks Liskov substitution, and how to fix the family tree: inherit a promise, not just code.
Your aunt leaves you her sailboat. It’s a lovely boat. There’s just one problem: you get
seasick. So you don’t sell it. You tape a note to the side: Do not sail. But everyone who
reads the will still expects a sailor. Code does this too. An electric car inherits from
Car, and with it, a method to refuel. It can’t refuel, so it refuses. This code smell is
called Refused Bequest (a bequest is what you inherit in a will).
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Inheritance hands a subclass everything its parent has, wanted or not. When the subclass can’t use part of it, it refuses, but the type still promises that every car can be refueled.
In this lesson we’ll see what it looks like, why it hurts, how to spot it, and how to fix the family tree.
Here’s a car-sharing app. The Car class can drive, refuel and change its oil, and it keeps
track of the fuel level:
class Car {
protected double fuelLevel;
void drive(double km) { ... }
void refuel(double liters) { fuelLevel += liters; }
void changeOil() { ... }
}Then the company buys electric cars. An electric car is a car, right? So it extends Car.
But it has no fuel tank:
class ElectricCar extends Car {
private double batteryLevel;
@Override
void refuel(double liters) {
throw new UnsupportedOperationException("no fuel tank");
}
@Override
void changeOil() { } // nothing to change
}refuel throws an UnsupportedOperationException. That’s a loud refusal.changeOil is overridden with an empty body. That’s a quiet refusal.fuelLevel field is still there, always zero: an unused inheritance.Martin Fowler calls this smell Refused Bequest in Refactoring: a subclass that uses only some of what it inherits, and refuses the rest.
Look at the nightly service job. It goes through the whole fleet, refuels every car, and changes the oil:
void nightlyService(List<Car> fleet) {
for (Car car : fleet) {
car.refuel(40);
car.changeOil();
}
}It compiles. It even works, until the first electric car rolls in. Then it crashes, at runtime, in the middle of the night. The compiler couldn’t warn you, because the type said every car can refuel.
The empty override is even sneakier. It doesn’t crash. It just does nothing, and the service log says the oil was changed.
So the callers start defending themselves: if this car isn’t an electric car, then refuel it:
for (Car car : fleet) {
if (!(car instanceof ElectricCar)) {
car.refuel(40);
car.changeOil();
}
}Now the job knows about every subclass. Add a hydrogen car next year, and you have to find every one of these checks.
| Refusal | What callers see | Cost |
|---|---|---|
| throws | a runtime crash | outages the compiler can’t catch |
| does nothing | false success | silent lies in logs and data |
| unused field | misleading state | confusion, wasted memory |
instanceof guards | type checks everywhere | every new subclass edits every caller |
A refused method breaks every caller that trusted the parent.
There’s a principle behind this: the Liskov Substitution Principle (Barbara Liskov, 1987). Anywhere the program expects a parent, a child must work, with no surprises. In other words:
A subclass must keep every promise its parent makes.
Here’s the classic puzzle. Is a square a rectangle? In geometry, yes. So Square extends
Rectangle, and setting the width also sets the height:
class Square extends Rectangle {
@Override
void setWidth(int w) { this.width = w; this.height = w; }
@Override
void setHeight(int h) { this.width = h; this.height = h; }
}Now this method stretches a rectangle: width five, height four. The area should be twenty:
void stretch(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
assert r.area() == 20; // a Square gives 16
}Pass in a square, and setting the height drags the width along with it. The area is sixteen. The square refused the rectangle’s promise that width and height change independently.
So in geometry, a square is a rectangle. In behavior, it isn’t. (The usual fixes: make both
immutable value objects, or give them a common Shape parent instead of an is-a link.)
How do you spot a refused bequest? Look for five signals.
UnsupportedOperationException (or IllegalStateException,
“not implemented”, and friends).return null, return 0).instanceof checks in the code that uses the class, treating one subclass differently.A note that says don’t use this is the smell, written down. Just like the note on the sailboat.
So what’s the fix? Start with the key idea: inheritance is a promise to every caller. It’s not a way to copy code.
Inherit a promise, not just code. If you’d refuse it, don’t inherit it.
Then ask one question: is the is-a real?
If the is-a is real, but the parent promises too much, reshape the family tree. Push Down
Method and Push Down Field move refuel, changeOil and the fuel level into a new class,
FuelCar. That leaves Extract Superclass: Car keeps only what every car truly shares,
driving. And the electric car gets its own method, charge. Now it has nothing to refuse. The
sailboat went to the cousin who sails.
abstract class Car {
void drive(double km) { ... }
}
class FuelCar extends Car {
private double fuelLevel;
void refuel(double liters) { fuelLevel += liters; }
void changeOil() { ... }
}
class ElectricCar extends Car {
private double batteryLevel;
void charge(double kWh) { batteryLevel += kWh; }
}And every class in the tree keeps every promise it makes.
But what about the nightly job? It doesn’t really care what kind of car it has. It needs
something that can be serviced. So Extract Interface: Serviceable, with one method,
service():
interface Serviceable {
void service();
}
void nightlyService(List<Serviceable> fleet) {
for (Serviceable s : fleet) {
s.service();
}
}Each car services itself its own way. A fuel car refuels and changes the oil; an electric car
charges. No refusals, and no instanceof checks. And when the hydrogen car arrives, the job
doesn’t change at all.
Depend on the capability, not on the family tree.
Here’s a real example, from Java itself: java.util.Stack extends Vector. A stack should only
push, pop and peek: last in, first out. But because it extends Vector, it also inherits every
list operation. So you can insert a page at the bottom, or remove one from the middle:
Stack<String> history = new Stack<>();
history.push("home");
history.push("search");
history.add(0, "sneaky"); // inherited from Vector
history.remove(1); // so is thisIt’s not a stack anymore. It accepted rules it should have refused. Here, the is-a is false: a
stack is not a kind of vector. So the main fix is Replace Inheritance with Delegation. Hold
the other object in a field, and expose only what you mean. This History class keeps a deque
inside, and offers push, pop and peek. Nothing else:
class History {
private final Deque<String> pages = new ArrayDeque<>();
void push(String page) { pages.push(page); }
String pop() { return pages.pop(); }
String peek() { return pages.peek(); }
}In fact, the Java documentation itself now recommends a Deque (for example ArrayDeque)
instead of the old Stack class. Delegation is also what people mean by composition over
inheritance.
If the is-a is false, use has-a.
Not every refusal is equally bad. Fowler separates two strengths:
| Refusing implementation | Refusing the interface | |
|---|---|---|
| What happens | a subclass never calls a protected helper it inherited | a subclass breaks the parent’s public promise (throws, does nothing) |
| Who notices | nobody outside the class | every caller that trusts the type |
| Verdict | mild, often fine | the real smell (breaks Liskov) |
You’ll see a related shape in the Template Method pattern. When subclasses fight the base class’s skeleton with empty or throwing steps, the skeleton is wrong for them:
So when is a little refusal acceptable?
void onStart() { } // optional).List contract says so up front (“optional operation”). It’s a deliberate trade-off, but it
can still surprise a caller:List<String> days = Collections.unmodifiableList(all);
days.get(0); // fine
days.add("Funday"); // throws UnsupportedOperationExceptionSo the test is simple. Can every caller trust the parent’s promise?
A refused bequest is a subclass that doesn’t want what it inherits. It throws, it does nothing, or it carries fields it never uses. That breaks the Liskov Substitution Principle. If the is-a is real, push down what doesn’t belong, extract a superclass, and let callers depend on an interface. If the is-a is false, replace inheritance with delegation.
instanceof checks that grow with every subclass.Square vs Rectangle).Stack vs Vector).If you’d refuse it, don’t inherit it. Inherit a promise, not just code.