# Inheritance and Composition: Is-a and Has-a

Two ways to build a class from another: inheritance, where an e-bike is a bike and overrides its price, and composition, where a bike has a lock it keeps as a field; saying the relationship aloud, is-a or has-a, tells you which one fits.

Apprentice · OOP · C# · Java · Python · JavaScript · TypeScript · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Choose between inheritance and composition by saying the relationship aloud: is-a or has-a
- Write a subclass that overrides a method, and a class that holds another object as a field

## Key takeaways

- Inheritance makes a new class from an old one: the subclass gets everything the parent has, and can override what differs.
- Composition builds a class from parts: it keeps another object in a field and uses it.
- Say it aloud: "an e-bike is a bike" means inheritance; "a bike has a lock" means composition.
- When "is a" sounds wrong, inheritance is wrong, even if it would save a few lines.

**Before this:** *Polymorphism: One Call, Many Behaviors*, where each class answers `price(hours)` its own way.

Pedal & Go's e-bikes are bikes with a motor. They have a bell like any bike, they're rented the same way, and they cost more: $15 an hour instead of $10. Writing `EBike` from scratch means copying everything `Bike` already has, and the day the bell changes, there are two to change. Every bike also needs a lock, and so does every scooter. Which classes should share code, and how? Object-oriented languages give you two ways to build one class from another, and picking the wrong one is one of the most common design mistakes there is. Patterns use both, so it's worth getting this right now.

## Is-a: inheritance

When a new class is a more particular kind of an existing one, it can **inherit** from it. The new class, the **subclass** (or child), gets every field and method of the **parent** (or superclass), and changes only what's different. Replacing a parent's method with the subclass's own version is called **overriding** it.

```csharp
Bike bike = new Bike();
EBike ebike = new EBike();
Console.WriteLine($"{bike.Name}, 2 hours: ${bike.Price(2)}");
Console.WriteLine($"{ebike.Name}, 3 hours: ${ebike.Price(3)}");
Console.WriteLine($"{ebike.Name} bell: {ebike.Ring()}");
Console.WriteLine($"{ebike.Name} battery: {ebike.BatteryPercent}%");

class Bike
{
    public virtual string Name => "Bike";
    public virtual int Price(int hours) => 10 * hours;
    public string Ring() => "Ring ring!";
}

// An e-bike is a bike: it gets Ring() from Bike, and overrides what differs.
class EBike : Bike
{
    public override string Name => "E-bike";
    public override int Price(int hours) => 15 * hours;
    public int BatteryPercent { get; set; } = 80;
}
```

```text
Bike, 2 hours: $20
E-bike, 3 hours: $45
E-bike bell: Ring ring!
E-bike battery: 80%
```

```java
class Bike {
    String name() { return "Bike"; }
    int price(int hours) { return 10 * hours; }
    String ring() { return "Ring ring!"; }
}

// An e-bike is a bike: it gets ring() from Bike, and overrides what differs.
class EBike extends Bike {
    int batteryPercent = 80;

    @Override
    String name() { return "E-bike"; }

    @Override
    int price(int hours) { return 15 * hours; }
}

void main() {
    Bike bike = new Bike();
    EBike ebike = new EBike();
    IO.println(bike.name() + ", 2 hours: $" + bike.price(2));
    IO.println(ebike.name() + ", 3 hours: $" + ebike.price(3));
    IO.println(ebike.name() + " bell: " + ebike.ring());
    IO.println(ebike.name() + " battery: " + ebike.batteryPercent + "%");
}
```

```text
Bike, 2 hours: $20
E-bike, 3 hours: $45
E-bike bell: Ring ring!
E-bike battery: 80%
```

```python
class Bike:
    name = "Bike"

    def price(self, hours):
        return 10 * hours

    def ring(self):
        return "Ring ring!"


class EBike(Bike):
    """An e-bike is a bike: it gets ring() from Bike, and overrides what differs."""
    name = "E-bike"
    battery_percent = 80

    def price(self, hours):
        return 15 * hours


bike = Bike()
ebike = EBike()
print(f"{bike.name}, 2 hours: ${bike.price(2)}")
print(f"{ebike.name}, 3 hours: ${ebike.price(3)}")
print(f"{ebike.name} bell: {ebike.ring()}")
print(f"{ebike.name} battery: {ebike.battery_percent}%")
```

```text
Bike, 2 hours: $20
E-bike, 3 hours: $45
E-bike bell: Ring ring!
E-bike battery: 80%
```

```javascript
class Bike {
  name = "Bike";
  price(hours) { return 10 * hours; }
  ring() { return "Ring ring!"; }
}

// An e-bike is a bike: it gets ring() from Bike, and overrides what differs.
class EBike extends Bike {
  name = "E-bike";
  batteryPercent = 80;
  price(hours) { return 15 * hours; }
}

const bike = new Bike();
const ebike = new EBike();
console.log(`${bike.name}, 2 hours: $${bike.price(2)}`);
console.log(`${ebike.name}, 3 hours: $${ebike.price(3)}`);
console.log(`${ebike.name} bell: ${ebike.ring()}`);
console.log(`${ebike.name} battery: ${ebike.batteryPercent}%`);
```

```text
Bike, 2 hours: $20
E-bike, 3 hours: $45
E-bike bell: Ring ring!
E-bike battery: 80%
```

```typescript
class Bike {
  name = "Bike";
  price(hours: number): number { return 10 * hours; }
  ring(): string { return "Ring ring!"; }
}

// An e-bike is a bike: it gets ring() from Bike, and overrides what differs.
class EBike extends Bike {
  name = "E-bike";
  batteryPercent = 80;
  price(hours: number): number { return 15 * hours; }
}

const bike = new Bike();
const ebike = new EBike();
console.log(`${bike.name}, 2 hours: $${bike.price(2)}`);
console.log(`${ebike.name}, 3 hours: $${ebike.price(3)}`);
console.log(`${ebike.name} bell: ${ebike.ring()}`);
console.log(`${ebike.name} battery: ${ebike.batteryPercent}%`);
```

```text
Bike, 2 hours: $20
E-bike, 3 hours: $45
E-bike bell: Ring ring!
E-bike battery: 80%
```

`EBike` never mentions the bell, and it rings anyway: `Ring()` came from `Bike`. The words for "inherits from" differ: `: Bike` in C#, `extends Bike` in Java, JavaScript and TypeScript, and `(Bike)` in Python. C# also asks the parent to mark what may be overridden (`virtual`) and the child to say it's overriding (`override`); Java's `@Override` is optional but catches typos. And because an e-bike is a bike, a variable of type `Bike` can hold one, and calling `price` on it runs the e-bike's version: that's polymorphism again, through inheritance this time.

## Has-a: composition

Now the locks. Every bike and every scooter has a code lock, and a lock has its own job: knowing its code and opening for the right one. It's tempting to make `Bike` inherit from the lock class, so a bike gets `open` for free. Say it aloud: "a bike is a lock". It isn't. A bike **has** a lock.

When one object has another as a part, the class keeps the part in a field. Building a class from parts like this is called **composition**:

![Is-a and has-a side by side: on the left, inheritance, an E-bike with a hollow-triangle arrow up to Bike, labeled "is a"; on the right, composition, a Bike joined by a plain line to a Code lock, labeled "has a"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/5499676de96f402e8b79f33533d337ec.webp)

```csharp
Bike bike = new Bike(new CodeLock("4321"));
Scooter scooter = new Scooter(new CodeLock("1111"));
Console.WriteLine($"Bike, code 1234: {bike.Lock.Open("1234")}");
Console.WriteLine($"Bike, code 4321: {bike.Lock.Open("4321")}");
Console.WriteLine($"Scooter, code 1111: {scooter.Lock.Open("1111")}");

class CodeLock
{
    private readonly string code;

    public CodeLock(string code)
    {
        this.code = code;
    }

    public string Open(string tried) => tried == code ? "Unlocked" : "Wrong code";
}

// A bike has a lock: it keeps one in a field.
class Bike
{
    public CodeLock Lock { get; }

    public Bike(CodeLock codeLock)
    {
        Lock = codeLock;
    }
}

class Scooter
{
    public CodeLock Lock { get; }

    public Scooter(CodeLock codeLock)
    {
        Lock = codeLock;
    }
}
```

```text
Bike, code 1234: Wrong code
Bike, code 4321: Unlocked
Scooter, code 1111: Unlocked
```

```java
class CodeLock {
    private final String code;

    CodeLock(String code) {
        this.code = code;
    }

    String open(String tried) {
        return tried.equals(code) ? "Unlocked" : "Wrong code";
    }
}

// A bike has a lock: it keeps one in a field.
class Bike {
    final CodeLock lock;

    Bike(CodeLock lock) {
        this.lock = lock;
    }
}

class Scooter {
    final CodeLock lock;

    Scooter(CodeLock lock) {
        this.lock = lock;
    }
}

void main() {
    Bike bike = new Bike(new CodeLock("4321"));
    Scooter scooter = new Scooter(new CodeLock("1111"));
    IO.println("Bike, code 1234: " + bike.lock.open("1234"));
    IO.println("Bike, code 4321: " + bike.lock.open("4321"));
    IO.println("Scooter, code 1111: " + scooter.lock.open("1111"));
}
```

```text
Bike, code 1234: Wrong code
Bike, code 4321: Unlocked
Scooter, code 1111: Unlocked
```

```python
class CodeLock:
    def __init__(self, code):
        self._code = code

    def open(self, tried):
        return "Unlocked" if tried == self._code else "Wrong code"


class Bike:
    """A bike has a lock: it keeps one in a field."""

    def __init__(self, lock):
        self.lock = lock


class Scooter:
    def __init__(self, lock):
        self.lock = lock


bike = Bike(CodeLock("4321"))
scooter = Scooter(CodeLock("1111"))
print(f"Bike, code 1234: {bike.lock.open('1234')}")
print(f"Bike, code 4321: {bike.lock.open('4321')}")
print(f"Scooter, code 1111: {scooter.lock.open('1111')}")
```

```text
Bike, code 1234: Wrong code
Bike, code 4321: Unlocked
Scooter, code 1111: Unlocked
```

```javascript
class CodeLock {
  #code;

  constructor(code) {
    this.#code = code;
  }

  open(tried) {
    return tried === this.#code ? "Unlocked" : "Wrong code";
  }
}

// A bike has a lock: it keeps one in a field.
class Bike {
  constructor(lock) {
    this.lock = lock;
  }
}

class Scooter {
  constructor(lock) {
    this.lock = lock;
  }
}

const bike = new Bike(new CodeLock("4321"));
const scooter = new Scooter(new CodeLock("1111"));
console.log(`Bike, code 1234: ${bike.lock.open("1234")}`);
console.log(`Bike, code 4321: ${bike.lock.open("4321")}`);
console.log(`Scooter, code 1111: ${scooter.lock.open("1111")}`);
```

```text
Bike, code 1234: Wrong code
Bike, code 4321: Unlocked
Scooter, code 1111: Unlocked
```

```typescript
class CodeLock {
  #code: string;

  constructor(code: string) {
    this.#code = code;
  }

  open(tried: string): string {
    return tried === this.#code ? "Unlocked" : "Wrong code";
  }
}

// A bike has a lock: it keeps one in a field.
class Bike {
  lock: CodeLock;

  constructor(lock: CodeLock) {
    this.lock = lock;
  }
}

class Scooter {
  lock: CodeLock;

  constructor(lock: CodeLock) {
    this.lock = lock;
  }
}

const bike = new Bike(new CodeLock("4321"));
const scooter = new Scooter(new CodeLock("1111"));
console.log(`Bike, code 1234: ${bike.lock.open("1234")}`);
console.log(`Bike, code 4321: ${bike.lock.open("4321")}`);
console.log(`Scooter, code 1111: ${scooter.lock.open("1111")}`);
```

```text
Bike, code 1234: Wrong code
Bike, code 4321: Unlocked
Scooter, code 1111: Unlocked
```

The lock's code is written once, in `CodeLock`, and the bike and the scooter each **have** one. Bikes and scooters don't have to be related for that to work. Swapping a bike's lock for a new one is giving it a different object, not rewriting its class. The class is called `CodeLock` rather than `Lock` because .NET and TypeScript's web types already have a class named `Lock`, and two classes with one name in the same place won't compile.

`a ? b : c` in four of the languages, and `b if a else c` in Python, is a short `if`: it's read "if `a`, then `b`, otherwise `c`".

## Say it aloud

Two sentences decide it:

| Sentence | True? | So |
|---|---|---|
| An e-bike **is a** bike | yes | inheritance can fit |
| A bike **is a** lock | no | not inheritance |
| A bike **has a** lock | yes | composition |
| A scooter **is a** bike | no: no pedals, no bell | not inheritance, even though both are rented |

The last row is the trap. A scooter and a bike are both things you rent, and inheriting would save a line or two. But a scooter that inherits `Ring()` has a bell it doesn't have, and every change to `Bike` now reaches scooters too. What they share is a promise, `Rentable`, which is an interface, not a parent.

Inheritance ties a child to its parent for good: every change to the parent reaches every child, and in C# and Java a class can have only one parent. Composition is looser: a part can be swapped, shared or tested on its own. Both are tools patterns use; *Prefer Composition to Inheritance*, later in this module, shows what happens to a family of subclasses that grows too far.

**Try it.** In the second program, give the scooter a new lock with the code `"2468"`. The scooter's line now says `Wrong code`, and neither class changed: only the part did. Then look back at the first program: "an e-bike has a battery" is true too, and the battery is a field, so the e-bike uses inheritance and composition at once.

## Check yourself

2 questions to try on the lesson page.

## So what

"Is a" or "has a", said aloud, settles most design arguments about inheritance in one sentence, and it's the first question to ask before writing `extends`.

## Key terms

- [Inheritance](https://www.ask-codey.com/glossary/inheritance-oop)
- [Composition](https://www.ask-codey.com/glossary/composition-oop)
- [Is-a vs Has-a](https://www.ask-codey.com/glossary/is-a-vs-has-a)
- [Method Overriding](https://www.ask-codey.com/glossary/method-overriding-oop)

## Cheat sheets

- [Inheritance and Composition: Is-a and Has-a](https://www.ask-codey.com/cheat-sheets/dp-inheritance-and-composition-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-inheritance-and-composition
