Thuta Learning
Java
AdvancedProgrammingBeginner

Inheritance

JavaLesson 1930 min

What you'll walk away with

  • Write a subclass with extends and say which members it inherits and which it does not
  • Call super(...) from a subclass constructor and explain the order in which constructors run
  • Override a method with @Override and reuse the parent version through super.method()
  • Tell is-a from has-a and recognise when composition is a better choice than inheritance

Explain it simply

Inheritance in plain language

Inheritance means building a new class on top of an existing one, so the new class starts with the existing class's fields and methods. The original class is the superclass (or parent) and the new one is the subclass (or child). In Java you write class Car extends Vehicle, and Car automatically gets what Vehicle offers, so you only write the parts that are new.

Think about job titles. Every doctor is an employee: they have a name, get a salary and show up to work. A doctor also has extra duties, like seeing patients. When you can honestly say "an X is a kind of Y", inheritance is a natural fit.

Problem → Why → Solution

The problem: the same code copied into three classes

Imagine a rental app with three classes: Car, Motorcycle and Truck. Each one has its own copy of a brand field and a start() method. One day a new rule arrives: start() must check the fuel before the engine turns on. You fix Car, forget Truck, and trucks with empty tanks keep getting dispatched.

Vehicles.java
class Car {
  String brand;
  void start() { System.out.println(brand + " is starting..."); }
}

class Motorcycle {
  String brand;   // same field again
  void start() { System.out.println(brand + " is starting..."); }
}

class Truck {
  String brand;   // and again: a fix in Car never reaches this copy
  void start() { System.out.println(brand + " is starting..."); }
}

Why copied code is dangerous

Three copies means three places to fix, and forgetting one is a bug. Worse, Java sees no relationship between the three classes, so you cannot write one method that accepts "any vehicle". Inheritance puts the shared behaviour in one place, Vehicle, and tells the compiler that Car, Motorcycle and Truck are all kinds of Vehicle.

Core concept: extends, super and overriding

When you write class Car extends Vehicle, every Car object contains a Vehicle part. Car can use Vehicle's public and protected members as if they were its own, plus members with no modifier when both classes are in the same package. Private fields still exist inside the object, but Car's code cannot name them; it has to go through the parent's methods.

Constructors are not inherited. Every subclass constructor must call a parent constructor with super(...) as its very first statement. If you write nothing, the compiler inserts a no-argument super() for you, and if the parent has no such constructor you get a compile error. The result is that building an object runs constructors from the top down: Object first, then the parent, then the child.

text
new Car("Ford", "Mustang")
--------------------------
new Car("Ford", "Mustang")
   |
   v
Car(...) { super(brand); ... }   <- first line calls the parent
   |
   v
Vehicle(...) { this.brand = brand; }   <- implicit super() to Object
   |
   v
Object()   -> returns, then Vehicle finishes, then Car finishes

One object in memory:
+----------------------------------+
| Object part                      |
| Vehicle part: brand = "Ford"     |
| Car part:     modelName="Mustang"|
+----------------------------------+

When a subclass writes a method with the same name and parameter list as a parent method, it overrides it. Put the @Override annotation on it: if a typo in the signature turns your override into an unrelated new method, the compiler stops you immediately. Inside the override, super.start() calls the parent's version, so you can add to the behaviour instead of rewriting it.

A Java class can extend exactly one superclass (single inheritance), and a class with no extends clause extends java.lang.Object. That is why every object you create already has toString(), equals() and hashCode(), and why you can print any object before writing those methods yourself. You can stop all extension with final, and since Java 17 a sealed class can list exactly which subclasses are permitted. Do not treat inheritance as a mere code-reuse tool: it is a promise that a subclass object can stand in anywhere the parent is expected.

A subclass is a layer on top of its parent
  1. Parent owns shared fields and methods
  2. Child gets them through extends
  3. Child constructor calls super(...) first
  4. Child adds new members or overrides

If the sentence "a child is a kind of parent" is false, do not use extends; holding the other object in a field (composition) fits better.

General pattern

java
class Parent {
  Parent(Type value) { ... }
  ReturnType method() { ... }
}

class Child extends Parent {
  Child(Type value, Type extra) {
    super(value);          // must be the first statement
  }
  @Override
  ReturnType method() { super.method(); ... }
}

The child names its parent with extends, calls super(...) first in its constructor, marks overriding methods with @Override, and reuses the parent's logic with super.method() when it needs it.

Worked example: Vehicle and Car

Vehicle owns what every vehicle has: a brand and a start() method. Car takes those through extends, adds a modelName, and overrides start(). The last println shows that a Car object can read both the inherited brand and its own modelName.

Main.java
public class Main {
  public static void main(String[] args) {
    Car myCar = new Car("Ford", "Mustang");
    myCar.start();
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

class Vehicle {
  protected String brand;

  Vehicle(String brand) {
    this.brand = brand;
  }

  void start() {
    System.out.println(brand + " vehicle is starting...");
  }
}

class Car extends Vehicle {
  String modelName;

  Car(String brand, String modelName) {
    super(brand);
    this.modelName = modelName;
  }

  @Override
  void start() {
    super.start();
    System.out.println(modelName + " is ready to drive.");
  }
}

Code breakdown

  1. Parent fieldprotected String brand;

    protected lets subclasses (and classes in the same package) read brand directly. If it were private, writing brand inside Car would be a compile error.

  2. Declare the subclassclass Car extends Vehicle {

    extends Vehicle makes Car a kind of Vehicle: every Car has brand and start(), and a Car can be passed anywhere a Vehicle is needed.

  3. Call the parent constructorsuper(brand);

    Vehicle only has a constructor that takes a String, so Car must call super(brand) on its first line. Remove it and the compiler tries super(), finds no no-arg constructor, and fails.

  4. Override and extendsuper.start();

    Car's start() runs the parent's version first and then prints its own line, which is why the first two output lines come from two different methods, in order.

  5. Use inherited and own membersSystem.out.println(myCar.brand + " " + myCar.modelName);

    myCar.brand is inherited from Vehicle and myCar.modelName belongs to Car. Main can read both because all three classes share a package.

You should see
Ford vehicle is starting...
Mustang is ready to drive.
Ford Mustang

Is-a or has-a: inheritance versus composition

A Car is a Vehicle (is-a), but a Car has an Engine (has-a); a car is not a kind of engine. Expressing has-a with a field is called composition. Composition couples Car only to Engine's public methods, so Engine's internals can change without breaking Car, and swapping in an ElectricEngine is easy.

Garage.java
public class Garage {
  public static void main(String[] args) {
    Truck truck = new Truck("Volvo", new Engine(420));
    truck.start();
  }
}

class Engine {
  private final int horsepower;
  Engine(int horsepower) { this.horsepower = horsepower; }
  String ignite() { return horsepower + " hp engine running"; }
}

class Truck {
  private final String brand;
  private final Engine engine;   // has-a: composition, not extends

  Truck(String brand, Engine engine) {
    this.brand = brand;
    this.engine = engine;
  }

  void start() {
    System.out.println(brand + ": " + engine.ignite());
  }
}
QuestionChoose
Is the child truly a kind of parent and usable in its place?extends (inheritance)
Does one class merely use another object's abilities?A field (composition)
Do you want to control exactly which subclasses exist?sealed ... permits
Should nobody be able to extend it?final class

In real projects

Inheritance in real projects

The JDK itself uses inheritance everywhere. Exceptions form a large hierarchy: IllegalArgumentException extends RuntimeException, which extends Exception, so a single catch (RuntimeException e) handles every subclass. Writing your own exception classes, such as InsufficientFundsException extends RuntimeException, is one of the most common uses of inheritance in application code.

  • Domain models: AdminUser extends User reuses every user's login and profile logic and adds only admin permissions. Every admin really is a user, so the is-a test passes.
  • Framework base classes: libraries such as Swing (JPanel) or test frameworks often hand you a class to extend, where you override only a few methods.
  • Teams keep hierarchies shallow, two or three levels, and mark methods that must not change as final, so editing the parent does not silently break subclasses.

Common mistakes

Common mistakes with inheritance

Forgetting to call the parent constructor

If Vehicle only has Vehicle(String brand) and you write Car(String model) { this.model = model; }, the compiler inserts super() and reports "constructor Vehicle in class Vehicle cannot be applied to given types". The fix is to call super(brand) yourself on the first line of Car's constructor.

Reaching for the parent's private field

If brand is private in Vehicle, brand.toUpperCase() inside Car fails with "brand has private access in Vehicle". Adding a getBrand() method to the parent is usually better than making everything protected, because the parent keeps control of its own data.

Extending just to borrow code

A Stack that extends ArrayList gets push and pop, but it also inherits add(0, x) and remove(index), which break the stack's rules. The JDK's own java.util.Stack extends Vector and has exactly this problem; its documentation recommends Deque instead. Keeping the list in a private field (composition) is the right fix.

Skipping @Override and overloading by accident

Writing void start(int speed) or void Start() in the child, when the parent has void start(), creates a new method instead of an override, and the parent's version keeps running. With @Override the compiler catches it at once: "method does not override or implement a method from a supertype".

Best practices

Best practices

  • Put @Override on every overriding method.
  • Keep fields private and expose what subclasses need through protected methods or getters.
  • Keep hierarchies shallow and close classes that are not designed for extension with final.
  • Use extends only when "X is a kind of Y" is true; otherwise choose composition.

Mini challenge

Mini challenge: Employee and Manager

Write an Employee class and a Manager class that extends it. Employee holds a name and a yearly salary and computes monthly pay. Manager also takes a yearly bonus and adds one twelfth of it to the monthly pay.

  • Keep Employee's fields private and expose a name() getter
  • Manager's constructor must call the Employee constructor with super(...)
  • Manager overrides monthlyPay() with @Override and reuses super.monthlyPay()
  • Print describe() for both objects without rewriting describe() in Manager
Payroll.java
public class Payroll {
  public static void main(String[] args) {
    // TODO: create an Employee "Aye" with 36000 a year
    // TODO: create a Manager "Min" with 60000 a year and a 12000 bonus
    // TODO: print describe() for both
  }
}

class Employee {
  // TODO: private name and yearlySalary fields + a constructor

  String name() {
    // TODO
  }

  double monthlyPay() {
    // TODO: yearly salary divided by 12
  }

  String describe() {
    // TODO: "<name> earns <pay with 2 decimals> per month"
  }
}

// TODO: class Manager extends Employee with a bonus field,
// a constructor that calls super(...), and an @Override of monthlyPay()

Expected: Two lines: "Aye earns 3000.00 per month" and "Min earns 6000.00 per month" (5000 salary plus 1000 bonus).

Show hint

If describe() calls monthlyPay(), a Manager object runs Manager's override, so describe() never needs rewriting. Use String.format("%.2f", value) for two decimals.

Show solution
Payroll.java
public class Payroll {
  public static void main(String[] args) {
    Employee aye = new Employee("Aye", 36000);
    Manager min = new Manager("Min", 60000, 12000);
    System.out.println(aye.describe());
    System.out.println(min.describe());
  }
}

class Employee {
  private final String name;
  private final double yearlySalary;

  Employee(String name, double yearlySalary) {
    this.name = name;
    this.yearlySalary = yearlySalary;
  }

  String name() {
    return name;
  }

  double monthlyPay() {
    return yearlySalary / 12;
  }

  String describe() {
    return name() + " earns " + String.format("%.2f", monthlyPay()) + " per month";
  }
}

class Manager extends Employee {
  private final double yearlyBonus;

  Manager(String name, double yearlySalary, double yearlyBonus) {
    super(name, yearlySalary);
    this.yearlyBonus = yearlyBonus;
  }

  @Override
  double monthlyPay() {
    return super.monthlyPay() + yearlyBonus / 12;
  }
}

Quick quiz 1 / 3

Given class A { A() { System.out.print("A"); } } and class B extends A { B() { System.out.print("B"); } }, what does new B(); print?

Quick quiz 2 / 3

Vehicle has only a Vehicle(String brand) constructor. What happens with class Car extends Vehicle { Car() { System.out.println("car"); } }?

Quick quiz 3 / 3

Which relationship below is the best fit for extends?

What to remember

  • extends gives a subclass the superclass's fields and methods, though private members cannot be named directly.
  • Constructors are not inherited: every subclass constructor calls super(...) first, so the parent part is initialised first.
  • Change behaviour with @Override and reuse the parent's logic with super.method().
  • A Java class extends exactly one superclass; when is-a is not true, prefer composition.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Inheritance | Thuta Learning