Skip to content

Intermediate · Inheritance, polymorphism and interfaces · topic 21 of 60 · 25 min

Inheritance with extends

Explanation

A subclass extends a superclass to reuse its fields and methods and add or change behaviour. It models an "is-a" relationship: a SavingsAccount is an Account. The subclass constructor calls the parent constructor with super(...). A Java class can extend only one class, and every class ultimately extends Object.

Why inheritance?

A bank has savings accounts, current accounts and fixed deposits. All have an account number, an owner and a balance, and can show a statement. Copying that code into three classes means fixing every bug three times. Inheritance puts the shared part in one superclass (parent) and lets subclasses (children) add only what is different.

java
public class Account {
    private final String number;
    protected double balance;            // visible to subclasses (see topic 5)

    public Account(String number, double opening) {
        this.number = number;
        this.balance = opening;
    }
    public void deposit(double amt) { balance += amt; }
    public String getNumber() { return number; }
    public double getBalance() { return balance; }
}

public class SavingsAccount extends Account {
    private final double ratePercent;

    public SavingsAccount(String number, double opening, double ratePercent) {
        super(number, opening);          // run the parent's constructor first
        this.ratePercent = ratePercent;
    }
    public void addInterest() {
        balance += balance * ratePercent / 100;   // uses the inherited field
    }
}

SavingsAccount s = new SavingsAccount("SB-101", 10000, 4);
s.deposit(2000);        // inherited method
s.addInterest();        // its own method
System.out.println(s.getBalance());   // 12480.0

super(...) in constructors

Constructors are not inherited. A subclass constructor must first let the parent initialise its part, by calling super(...) with the right arguments. If you write no super call, Java inserts super() (the parent's no-argument constructor), which fails to compile if the parent does not have one. Traditionally super(...) must be the first statement; newer Java versions (25 and later) relax this slightly for statements that do not use this.

What is inherited

  • Public and protected fields and methods are inherited and usable in the subclass.
  • Private members exist inside the object but the subclass cannot touch them directly; it uses the parent's public or protected methods.
  • Constructors are NOT inherited.
  • Static members belong to the class and are accessible but not "overridden".

Single inheritance and Object

A Java class can extend exactly one class (class C extends A, B is not allowed). This avoids the confusion of a method inherited from two parents. A class can still implement many interfaces (topic 4). Every class without an extends clause automatically extends java.lang.Object, which is why every object has toString, equals and hashCode.

Careful: Do not use inheritance just to reuse code when the "is-a" sentence is false. A Car is not an Engine, so class Car extends Engine is wrong; a Car HAS an Engine (a field). Wrong inheritance creates fragile designs where a change in the parent breaks many children. When in doubt, prefer composition: put the other object in a field.
Think of it like this: Inheritance is like a family business: the son inherits the shop, the name board and the regular customers (fields and methods) and adds his own new counter (new methods). But he cannot inherit a "has-a" thing like his father's scooter by pretending to BE the scooter.
Tip: Keep hierarchies shallow, usually one or two levels. Deep trees (A → B → C → D → E) are hard to understand and change.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Inheritance with extends · 1/6

Inheritance

In this lesson you will build classes on top of other classes with inheritance.

Prefer a video by a teacher? Find free videos on “java inheritance extends super constructor tutorial” on YouTube ↗

In real life: Employees in an HR system

An HR system has full-time employees and contractors. Both have an id, a name and a joining date (in an Employee superclass); FullTimeEmployee adds a monthly salary and leave balance, Contractor adds a daily rate and contract end date. Shared reports work on the Employee part of every object.

java
class Employee {
    protected final String id, name;
    Employee(String id, String name) { this.id = id; this.name = name; }
}
class Contractor extends Employee {
    private final int dailyRate;
    Contractor(String id, String name, int dailyRate) { super(id, name); this.dailyRate = dailyRate; }
    int invoice(int days) { return days * dailyRate; }
}
// new Contractor("C-7", "Meena", 4000).invoice(20) → 80000

Practice (0/3 done)

Task 1 · Question

class A { A(int x) {} } class B extends A { B() { } } What happens?

Task 2 · Question

Which is a correct use of inheritance?

Task 3 · Practice

Write a class Vehicle (registrationNo, wheels, a method describe()) and two subclasses: Bike (wheels = 2, adds helmetIncluded) and Truck (wheels = 6, adds loadTonnes). Each subclass constructor must call super. Create one of each and call describe().

Quick quiz

Question 1

1.How many classes can a Java class directly extend?

Question 2

2.Which members are NOT inherited?

Question 3

3.What does super(…) do in a constructor?

Question 4

4.Which class does every Java class ultimately extend?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How many classes can a Java class directly extend?

Answer: One

Java has single inheritance for classes.

Which members are NOT inherited?

Answer: Constructors

Constructors are never inherited.

What does super(…) do in a constructor?

Answer: Calls the parent class constructor

It initialises the parent part of the object.

Which class does every Java class ultimately extend?

Answer: Object

java.lang.Object is the root of all classes.

class B extends A {} (no constructor). What does new B(1, 2) do?Related

Answer: Calls A's constructor with 1, 2

A missing constructor in a subclass passes all arguments to super automatically.

From Inheritance and composition

How many classes can a Kotlin class extend?Related

Answer: One

One superclass, but many interfaces.

From Inheritance and interfaces

What does super().__init__(name, salary) do in a child's __init__?Related

Answer: Runs the parent's __init__ to set up its attributes

super() refers to the parent, so the parent's setup code runs on this object.

From Inheritance and composition

How many classes can a Dart class extend?Related

Answer: One

Single inheritance; many interfaces and mixins.

From Inheritance, interfaces, mixins and extensions

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Inheritance, polymorphism and interfaces” before its exam: Overriding and polymorphism, Abstract classes, Interfaces, Packages and access modifiers.
  2. Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.

← Previous: toString, equals, hashCode and records