Java Inheritance

Inheritance lets one class take on the fields and methods of another. Instead of rewriting shared code, you build a general parent class and let more specific child classes extend it, adding only what makes them different.

Parent and child classes

In Java you create inheritance with the extends keyword. The class being extended is called the superclass (or parent), and the class doing the extending is the subclass (or child). The child automatically gains every non-private member of the parent, then adds its own.

  • The parent class holds the shared, general code.
  • The child class uses extends to inherit that code.
  • The child can add new fields and methods of its own.
  • The child can override a parent method to change its behavior.

Extending a class

// Parent class
class Animal {
  String name;

  public void eat() {
    System.out.println(name + " is eating.");
  }
}

// Child class inherits from Animal
class Dog extends Animal {
  public void bark() {
    System.out.println(name + " says woof!");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.name = "Rex";
    d.eat();  // inherited from Animal
    d.bark(); // defined in Dog
  }
}

A child class often needs to build on the parent's constructor. The super keyword calls the parent's constructor, letting the parent set up its own fields before the child adds to them.

Using super

class Vehicle {
  String brand;

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

class Car extends Vehicle {
  int doors;

  public Car(String brand, int doors) {
    super(brand); // call the parent constructor first
    this.doors = doors;
  }

  public static void main(String[] args) {
    Car c = new Car("Honda", 4);
    System.out.println(c.brand + " with " + c.doors + " doors");
    // Outputs: Honda with 4 doors
  }
}
Note: If you call super(...), it must be the very first statement inside the child constructor. This guarantees the parent is fully set up before the child adds anything.
Keyword / TermRole
extendsDeclares that a class inherits from another.
superclassThe parent class whose members are inherited.
subclassThe child class that inherits and extends the parent.
superCalls the parent's constructor or accesses its members.
final classA class marked final cannot be extended at all.
Note: Java supports single inheritance for classes, meaning a class can extend only one parent. To share behavior from multiple sources, you use interfaces instead.

Exercise: Java Inheritance

Which keyword does a Java class use to inherit from another class?