# Refused BequestA 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.

{{< lesson-video youtube="rSBdVtgJIto" title="Refused Bequest" >}}

## The sailboat you didn't want

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.

```mermaid {alt="The analogy mapped onto code: the inherited sailboat corresponds to the inherited refuel method, the do-not-sail note corresponds to throwing UnsupportedOperationException, and the readers of the will who expect a sailor correspond to callers that expect every Car to refuel." caption="The note on the boat is the exception in the code."}
flowchart LR
  A["Inherited sailboat"] --> B["inherited refuel()"]
  C["Note: do not sail"] --> D["throw new<br/>UnsupportedOperationException"]
  E["Readers of the will<br/>expect a sailor"] --> F["Callers expect<br/>every Car to refuel"]
  class A,C,E muted
  class B c6
  class D bad
  class F hl
```

In this lesson we'll see what it looks like, why it hurts, how to spot it, and how to fix the
family tree.

## What it looks like

Here's a car-sharing app. The `Car` class can drive, refuel and change its oil, and it keeps
track of the fuel level:

```java
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:

```java
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**.
- And the `fuelLevel` field is still there, always zero: an **unused inheritance**.

```mermaid {alt="Class diagram: ElectricCar extends Car. Car has fuelLevel, drive, refuel and changeOil. ElectricCar adds batteryLevel, overrides refuel to throw UnsupportedOperationException, and overrides changeOil with an empty body."}
classDiagram
  class Car {
    #double fuelLevel
    +drive(double km)
    +refuel(double liters)
    +changeOil()
  }
  class ElectricCar {
    -double batteryLevel
    +refuel(double liters)
    +changeOil()
  }
  Car <|-- ElectricCar
  note for ElectricCar "refuses refuel() and changeOil()"
```

Martin Fowler calls this smell **Refused Bequest** in *Refactoring*: a subclass that uses only
some of what it inherits, and refuses the rest.

## Why it hurts

Look at the nightly service job. It goes through the whole fleet, refuels every car, and
changes the oil:

```java
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.

```mermaid {alt="Sequence: the nightly service job calls refuel and changeOil on a petrol car, which succeeds, then calls refuel on an ElectricCar, which throws UnsupportedOperationException and stops the job." caption="It works until the first electric car rolls in."}
sequenceDiagram
  participant J as nightlyService
  participant F as Car (petrol)
  participant E as ElectricCar
  J->>F: refuel(40)
  F-->>J: ok
  J->>F: changeOil()
  F-->>J: ok
  J->>E: refuel(40)
  E--xJ: UnsupportedOperationException
  Note over J,E: the job crashes at runtime
```

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*:

```java
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.

```mermaid {alt="Adding a HydrogenCar subclass forces edits to every instanceof check: in the nightly service job, the billing code and the dashboard." caption="Every new subclass means a hunt for instanceof checks."}
flowchart LR
  H["+ HydrogenCar"] --> A["nightlyService<br/>instanceof check"]
  H --> B["Billing<br/>instanceof check"]
  H --> C["Dashboard<br/>instanceof check"]
  class H hl
  class A,B,C bad
```

| 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.**

## The principle: Liskov substitution

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:

```java
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:

```java
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.

```mermaid {alt="Flowchart: stretch sets width 5 and height 4. With a Rectangle the area is 20 as promised. With a Square, setting the height to 4 also sets the width to 4, so the area is 16 and the promise is broken." caption="In geometry a square is a rectangle; in behavior it isn't."}
flowchart TD
  S["stretch(r):<br/>setWidth(5), setHeight(4)"] --> R["Rectangle<br/>5 x 4 = 20"]
  S --> Q["Square<br/>height drags width:<br/>4 x 4 = 16"]
  R --> OK["promise kept"]
  Q --> NO["promise broken"]
  class S c5
  class R,OK good
  class Q,NO bad
```

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 to spot it

How do you spot a refused bequest? Look for five signals.

1. **Overrides that throw** an `UnsupportedOperationException` (or `IllegalStateException`,
   "not implemented", and friends).
2. **Empty overrides**, or ones that return a dummy value (`return null`, `return 0`).
3. **Inherited fields that are never used**, or always stay at their default.
4. **`instanceof` checks** in the code that uses the class, treating one subclass differently.
5. **The is-a only works by name.** You inherited to reuse some code, not because the child
   really is a kind of parent ("it's kind of like a car").

A note that says *don't use this* is the smell, written down. Just like the note on the
sailboat.

## The key insight: inherit a promise, not just code

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?

```mermaid {alt="Decision flowchart: a subclass refuses part of its inheritance. Is the is-a relationship real? If yes, but the parent promises too much, push down the members and extract a superclass, and let callers depend on an interface. If no, the subclass only wanted to reuse code, so replace inheritance with delegation." caption="Two ways out, depending on whether the is-a is real."}
flowchart TD
  A["A subclass refuses<br/>part of its inheritance"] --> Q{"Is the is-a<br/>real?"}
  Q -->|"yes, but the parent<br/>promises too much"| B["Push Down Method / Field<br/>Extract Superclass<br/>Extract Interface"]
  Q -->|"no, it only<br/>wanted the code"| C["Replace Inheritance<br/>with Delegation"]
  class A bad
  class Q warn
  class B,C good
```

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.

```java
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; }
}
```

```mermaid {alt="Class diagram after the refactoring: abstract Car with drive. FuelCar extends Car with fuelLevel, refuel and changeOil. ElectricCar extends Car with batteryLevel and charge. Neither subclass refuses anything."}
classDiagram
  class Car {
    <<abstract>>
    +drive(double km)
  }
  class FuelCar {
    -double fuelLevel
    +refuel(double liters)
    +changeOil()
  }
  class ElectricCar {
    -double batteryLevel
    +charge(double kWh)
  }
  Car <|-- FuelCar
  Car <|-- ElectricCar
```

And every class in the tree keeps every promise it makes.

## Callers ask for what they need

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()`:

```java
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.

```mermaid {alt="Class diagram: the Serviceable interface has one method, service. FuelCar and ElectricCar implement it, FuelCar by refueling and changing oil, ElectricCar by charging. nightlyService depends only on Serviceable."}
classDiagram
  class Serviceable {
    <<interface>>
    +service()
  }
  class FuelCar {
    +service()
  }
  class ElectricCar {
    +service()
  }
  Serviceable <|.. FuelCar
  Serviceable <|.. ElectricCar
  nightlyService ..> Serviceable
  note for FuelCar "refuel + change oil"
  note for ElectricCar "charge"
```

> **Depend on the capability, not on the family tree.**

## A real example: java.util.Stack

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:

```java
Stack<String> history = new Stack<>();
history.push("home");
history.push("search");
history.add(0, "sneaky");   // inherited from Vector
history.remove(1);          // so is this
```

It'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:

```java
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(); }
}
```

```mermaid {alt="Before: Stack is a Vector, so it inherits push, pop and peek plus add at an index, remove at an index, get and set. After: History has a Deque and exposes only push, pop and peek." caption="If the is-a is false, use has-a."}
flowchart TB
  subgraph BEFORE["Before: Stack is a Vector"]
    direction LR
    V["Vector<br/>add(i, e), remove(i),<br/>get(i), set(i, e)"] -->|inherited by| S["Stack<br/>push, pop, peek<br/>+ every Vector method"]
  end
  subgraph AFTER["After: History has a Deque"]
    direction LR
    H["History<br/>push, pop, peek"] -->|delegates to| D["Deque"]
  end
  BEFORE ~~~ AFTER
  class V c4
  class S bad
  class H good
  class D muted
```

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.**

## Commonly confused: refusing code vs refusing the interface

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](/patterns/template-method-pattern/).
When subclasses fight the base class's skeleton with empty or throwing steps, the skeleton is
wrong for them:

```mermaid {alt="Template Method skeleton with three steps, open, process and close. A subclass overrides process with an empty body and close with a throw, so the skeleton is wrong for that subclass." caption="Fighting the skeleton is a refused bequest in a template."}
flowchart TD
  T["Base class skeleton"] --> O["1 open()"]
  O --> P["2 process()"]
  P --> C["3 close()"]
  SP["subclass: process() { }"] -.-> P
  SC["subclass: close() { throw ... }"] -.-> C
  class T,O,P,C c6
  class SP,SC bad
```

## When it's acceptable

So when is a little refusal acceptable?

- **Harmless leftovers.** An inherited method that a subclass just doesn't need, that does no
  harm, and that no caller relies on, is fine. Like an old armchair in an inherited house:
  nobody sits in it, and nobody trips over it.
- **Documented optional hooks.** Optional hooks are fine too, when the base class documents
  them as optional, with an empty default that subclasses may fill in
  (`void onStart() { }   // optional`).
- **Documented optional operations.** Java's unmodifiable lists throw when you add to them. The
  `List` contract says so up front ("optional operation"). It's a deliberate trade-off, but it
  can still surprise a caller:

```java
List<String> days = Collections.unmodifiableList(all);
days.get(0);          // fine
days.add("Funday");   // throws UnsupportedOperationException
```

```mermaid {alt="Decision flowchart: a subclass does not use something it inherits. If no caller relies on it and it does no harm, leave it. If the base class documents it as an optional hook or operation, it is acceptable, but tell callers. If callers trust the parent's promise and get a throw or a silent no-op, it is Refused Bequest: fix the hierarchy." caption="The test: can every caller trust the parent's promise?"}
flowchart TD
  Q{"Can every caller trust<br/>the parent's promise?"} -->|"yes: unused,<br/>harmless"| A["Leave it"]
  Q -->|"documented as<br/>optional"| B["Acceptable,<br/>but surprising"]
  Q -->|"no: throws or<br/>silently does nothing"| C["Refused Bequest:<br/>fix the hierarchy"]
  class Q warn
  class A good
  class B amber
  class C bad
```

So the test is simple. Can every caller trust the parent's promise?

## Recap

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.

```mermaid {alt="Recap chain: spot the refusal (throws, empty overrides, unused fields, instanceof checks); ask whether the is-a is real; reshape the tree with Push Down, Extract Superclass and Extract Interface, or delegate; every subtype keeps its promises." caption="If you'd refuse it, don't inherit it."}
flowchart TD
  A["Spot the refusal<br/>throws, empty,<br/>unused, instanceof"] --> B{"Is the<br/>is-a real?"}
  B -->|yes| C["Push Down,<br/>Extract Superclass,<br/>Extract Interface"]
  B -->|no| D["Replace Inheritance<br/>with Delegation"]
  C --> E["Every subtype<br/>keeps its promises"]
  D --> E
  class A bad
  class B warn
  class C,D hl
  class E good
```

- **Refused Bequest**: a subclass uses only some of what it inherits and refuses the rest.
- **It hurts** because callers trust the parent: runtime crashes, silent no-ops, and
  `instanceof` checks that grow with every subclass.
- **Principle**: Liskov substitution. A subclass must keep every promise its parent makes
  (`Square` vs `Rectangle`).
- **Fix it**: Push Down Method/Field and Extract Superclass when the is-a is real, Extract
  Interface so callers depend on a capability, and Replace Inheritance with Delegation when the
  is-a is false (`Stack` vs `Vector`).
- **Leave it** when the unused part is harmless, or documented as optional.

If you'd refuse it, don't inherit it. **Inherit a promise, not just code.**

## Further reading

- Martin Fowler, *Refactoring: Improving the Design of Existing Code* (2nd ed.), chapter 3
  ("Refused Bequest") and the Push Down Method, Push Down Field, Extract Superclass and Replace
  Subclass with Delegate / Replace Superclass with Delegate refactorings.
- Barbara Liskov and Jeannette Wing, "A Behavioral Notion of Subtyping" (1994).
- Joshua Bloch, *Effective Java*, "Favor composition over inheritance".
- [Refactoring.Guru: Refused Bequest](https://refactoring.guru/smells/refused-bequest)
- Related lessons: [Template Method Pattern](/patterns/template-method-pattern/),
  [Large Class](/code-smells/large-class/) (Extract Subclass only for a true is-a),
  [Long Method](/code-smells/long-method/),
  [Feature Envy](/code-smells/feature-envy/),
  [Command Pattern](/patterns/command-pattern/),
  [Chain of Responsibility Pattern](/patterns/chain-of-responsibility-pattern/).
