DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

Inheritance: extending a class

Inheritance: extending a class

Suppose you are building two account types: a standard account and a savings account. Both have an ID, a balance, deposit and withdraw operations. The savings account also accrues interest. Without inheritance, you either duplicate the shared code or pull it into a utility class.

Inheritance gives a third option: declare the shared behaviour once in a superclass and extend it.

What extends means

The extends keyword creates a subclass that inherits the accessible members of its superclass.

public class Account {
    protected final String id;
    protected int balance;

    public Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
    }

    public void deposit(int amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    public void withdraw(int amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount > balance) throw new IllegalStateException("insufficient funds");
        balance -= amount;
    }

    public int getBalance() { return balance; }
}


public class SavingsAccount extends Account {
    private double interestRate;

    public SavingsAccount(String id, int initialBalance, double interestRate) {
        super(id, initialBalance);
        this.interestRate = interestRate;
    }

    public void applyInterest() {
        balance += (int)(balance * interestRate);
    }
}

Enter fullscreen mode Exit fullscreen mode

SavingsAccount inherits deposit, withdraw, and getBalance without redeclaring them. It adds applyInterest. Its constructor calls super(id, initialBalance) to initialize the fields declared in Account.

What a subclass inherits: all non-private fields and methods of its superclass. Private members exist in the superclass object but are not directly accessible from the subclass's code. The subclass can reach them only through the superclass's public or protected methods.

What a subclass does not inherit: constructors. Each class must declare its own constructors. A super(...) call invokes the superclass constructor, as covered in Initialization order.

Method overriding

A subclass can replace a superclass method by declaring a method with the same name and parameter list. This is called overriding.

public class SavingsAccount extends Account {
    // ...

    @Override
    public void withdraw(int amount) {
        if (amount > balance * 0.9) {
            throw new IllegalStateException("savings accounts require a 10% minimum balance");
        }
        super.withdraw(amount);
    }
}

Enter fullscreen mode Exit fullscreen mode

@Override is an annotation that tells the compiler you intend to override a superclass method. If the method signature doesn't match any superclass method, the compiler reports an error, a useful guard against typos like widthdraw.

super.withdraw(amount) calls the superclass version. Without it, the overriding method would have to reimplement the amount check and balance update. With it, the subclass adds its rule and delegates the rest.

The return type of an overriding method can be a subtype of the superclass method's return type. This is called a covariant return type. If Account.clone() returned Account, SavingsAccount.clone() could return SavingsAccount.

final: preventing extension and overriding

Marking a class final prevents it from being subclassed. Marking a method final prevents it from being overridden.

public final class AccountId {
    private final String value;
    // ...
}


public class Account {
    public final String getId() { return id; } // cannot be overridden
}

Enter fullscreen mode Exit fullscreen mode

String is a final class. No subclass can be created. This is part of what makes strings safe to use as map keys and cache entries: nothing can substitute a mutable String-like object in their place.

Use final when you need to guarantee that a class or method behaves exactly as written, with no possibility of a subclass changing that behaviour. The tradeoff is reduced extensibility.

The Object superclass

Every class in Java implicitly extends java.lang.Object if it has no explicit extends clause. Object provides default implementations of equals(), hashCode(), toString(), and a few other methods. This is why every Java object can be assigned to a variable of type Object and why every class has hashCode() without declaring it.

Objects, equality and identity covers what Object's default equals() and hashCode() do and why overriding them matters.

Inheritance versus composition

Inheritance models an "is-a" relationship: a SavingsAccount is an Account. Composition models a "has-a" relationship: an Account has a TransactionLog.

Inheritance is often overused. If a subclass overrides most of the superclass methods, or if the connection between the two classes is "shares some code" rather than a genuine type relationship, composition is usually cleaner.

// inheritance: SavingsAccount IS an Account
public class SavingsAccount extends Account { ... }

// composition: LimitedAccount HAS an Account
public class LimitedAccount {
    private final Account underlying;
    private final int dailyLimit;

    public void withdraw(int amount) {
        if (amount > dailyLimit) throw new IllegalStateException("daily limit exceeded");
        underlying.withdraw(amount);
    }
}

Enter fullscreen mode Exit fullscreen mode

With composition, LimitedAccount does not inherit the parts of Account it doesn't want. It delegates explicitly to what it needs and adds its own behaviour on top. Changes to Account that the LimitedAccount wasn't designed to handle won't silently affect it.

A rough guide: use inheritance when the subclass genuinely is a more specific version of the superclass type and can be used anywhere the superclass is expected. Use composition when you want to reuse behaviour without committing to that substitutability.

Prediction exercise

public class Base {
    public String describe() {
        return "Base";
    }
}

public class Child extends Base {
    @Override
    public String describe() {
        return super.describe() + " + Child";
    }
}

public class GrandChild extends Child {
    @Override
    public String describe() {
        return super.describe() + " + GrandChild";
    }
}

System.out.println(new GrandChild().describe());

Enter fullscreen mode Exit fullscreen mode

Predict the output. Then: if you mark Child.describe() as final, what changes at compile time and what changes at runtime?

Top comments (0)