Skip to content

Module 6 · Inheritance, Polymorphism and Interfaces — topic 1 of 3

Inheritance

Extending a class to reuse and specialise it: extends, super for constructors and methods, protected members, the Object root class, final classes and when to prefer composition.

Beginner 16 min read·Lesson 20 of 39 in Java Programming

Learning objectives

  • Create subclasses with extends and call superclass constructors with super(...)
  • Override methods and call the superclass version with super.method()
  • Decide between inheritance and composition

Definition

Inheritance lets a class (the subclass) acquire the fields and methods of another class (the superclass) using extends, modelling an 'is-a' relationship. Java supports single inheritance of classes; every class ultimately extends java.lang.Object.

Introduction

Many types are specialised versions of others: a savings account is a bank account that earns interest; a manager is an employee who also has a team. Inheritance lets you write the shared parts once in a superclass and add or change only what is different in each subclass.

Why it matters

Inheritance is how frameworks let you plug in your own behaviour — you extend their classes and override a few methods.

It is the foundation of polymorphism, the next lesson, which lets one piece of code work with many related types.

Detailed explanation

extends. class SavingsAccount extends Account gives SavingsAccount all the accessible fields and methods of Account. Private members are inherited as part of the object but can't be accessed directly; use protected members or public methods.

Constructors aren't inherited. A subclass constructor must call a superclass constructor with super(...) as its first statement. If you don't, the compiler inserts super(), which fails if the superclass has no no-argument constructor.

Overriding. A subclass can provide its own implementation of an inherited method with the same signature. Annotate it with @Override so the compiler checks you really are overriding. Inside it, super.method() calls the superclass's version.

Rules for overriding. The access can't be more restrictive (a public method stays public), the return type must be the same or a subtype, and the method can't throw broader checked exceptions. Static methods are *hidden*, not overridden.

Single inheritance. A class extends exactly one class. If you write no extends, it extends Object, which supplies toString, equals, hashCode and getClass.

final on a class (such as String) prevents subclassing; on a method it prevents overriding.

Composition over inheritance. Use inheritance only for a true 'is-a' relationship. If a class merely *uses* another — a Car has an Engine — store it as a field instead. Composition is more flexible and avoids fragile hierarchies.

Syntax

Java
class Account {
protected long balance;
Account(long opening) { balance = opening; }
String describe() { return "Account with " + balance; }
}
class SavingsAccount extends Account {
private final double rate;
SavingsAccount(long opening, double rate) {
super(opening); // must be first
this.rate = rate;
}
@Override
String describe() { return super.describe() + " at " + rate * 100 + "%"; }
}
  • super(...) must be the first statement of a constructor.
  • Always use @Override when overriding.
  • A subclass object can be used wherever its superclass is expected.

Code examples

Extending a class

Java
public class Main {
public static void main(String[] args) {
Employee e = new Employee("Ravi", 40_000);
Manager m = new Manager("Asha", 90_000, 5);
System.out.println(e.describe());
System.out.println(m.describe());
System.out.println(m.getName() + " bonus: " + m.bonus());
}
}
class Employee {
private final String name;
protected final long salary;
Employee(String name, long salary) {
this.name = name;
this.salary = salary;
}
String getName() { return name; }
String describe() { return name + " earns " + salary; }
}
class Manager extends Employee {
private final int teamSize;
Manager(String name, long salary, int teamSize) {
super(name, salary);
this.teamSize = teamSize;
}
long bonus() { return salary / 10 + teamSize * 1_000L; }
@Override
String describe() { return super.describe() + " and manages " + teamSize + " people"; }
}
Output
Ravi earns 40000
Asha earns 90000 and manages 5 people
Asha bonus: 14000

Constructor order

Java
public class Main {
public static void main(String[] args) {
new Puppy();
}
}
class Animal {
Animal() { System.out.println("Animal constructor"); }
}
class Dog extends Animal {
Dog() { System.out.println("Dog constructor"); }
}
class Puppy extends Dog {
Puppy() { System.out.println("Puppy constructor"); }
}
Output
Animal constructor
Dog constructor
Puppy constructor

Each constructor implicitly calls super() first, so construction runs from the top of the hierarchy down.

More examples

Accounts with overridden rules

Java
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Account> accounts = List.of(new Account("A1", 5_000), new SavingsAccount("S1", 5_000, 0.04), new CurrentAccount("C1", 5_000, 2_000));
for (Account a : accounts) {
boolean ok = a.withdraw(6_000);
a.monthEnd();
System.out.println(a + " withdraw 6000: " + ok);
}
}
}
class Account {
private final String id;
protected long balance;
Account(String id, long balance) { this.id = id; this.balance = balance; }
boolean withdraw(long amount) {
if (amount <= 0 || amount > available()) return false;
balance -= amount;
return true;
}
protected long available() { return balance; }
void monthEnd() { }
@Override public String toString() { return getClass().getSimpleName() + " " + id + " balance " + balance; }
}
class SavingsAccount extends Account {
private final double rate;
SavingsAccount(String id, long balance, double rate) { super(id, balance); this.rate = rate; }
@Override void monthEnd() { balance += Math.round(balance * rate / 12); }
}
class CurrentAccount extends Account {
private final long overdraft;
CurrentAccount(String id, long balance, long overdraft) { super(id, balance); this.overdraft = overdraft; }
@Override protected long available() { return balance + overdraft; }
@Override void monthEnd() { if (balance < 0) balance -= 100; } // overdraft fee
}
Output
Account A1 balance 5000 withdraw 6000: false
SavingsAccount S1 balance 5017 withdraw 6000: false
CurrentAccount C1 balance -1100 withdraw 6000: true

Step-by-step explanation

  • All three objects are stored as Account references in one list.
  • withdraw is written once in Account, but it calls available(), which CurrentAccount overrides to include the overdraft — so only C1 can withdraw 6000.
  • monthEnd() does nothing in Account; SavingsAccount adds a month's interest (5000 × 0.04 / 12 ≈ 17) and CurrentAccount charges a 100 fee when overdrawn.
  • getClass().getSimpleName() prints the real class of each object, even though the variable type is Account.
  • Subclasses access balance directly because it is protected; id stays private to Account.

Expected output

Running “Accounts with overridden rules” prints exactly:

TextOutput
Account A1 balance 5000 withdraw 6000: false
SavingsAccount S1 balance 5017 withdraw 6000: false
CurrentAccount C1 balance -1100 withdraw 6000: true

Practical applications

  • Framework base classes such as servlets or Android Activities
  • Exception hierarchies (IOException extends Exception)
  • GUI component hierarchies in Swing and JavaFX

Best practices

  • Use inheritance only for genuine is-a relationships.
  • Always annotate overriding methods with @Override.
  • Keep fields private and expose protected methods to subclasses when needed.

Common mistakes

Not calling the superclass constructor

Avoid

class Manager extends Employee {
Manager(String n) { } // implicit super() fails
}

Prefer

class Manager extends Employee {
Manager(String n) { super(n, 0); }
}

Employee has no no-argument constructor, so the implicit super() call doesn't compile.

Overloading when you meant to override

Avoid

public boolean equals(Point other) { ... }

Prefer

@Override
public boolean equals(Object other) { ... }

A different parameter type creates a new overload instead of overriding Object.equals; @Override would have caught the mistake.

Important notes

  • Deep hierarchies are hard to change; two or three levels are usually enough.
  • A class can implement many interfaces even though it can extend only one class (see the interfaces lesson).

Key takeaways

  • extends reuses a superclass's members; every class extends Object.
  • Subclass constructors call super(...) first; constructors run top-down.
  • Override with the same signature and @Override; super.method() calls the parent version.

Try it yourself

  1. 1
    Create Vehicle, Car and Truck classes where Truck overrides a toll() method based on axles.
  2. 2
    Add a Shape superclass with area() and subclasses Circle and Square.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerHow many classes can a Java class directly extend?
  • BeginnerWhat is printed?
Practise this topic