Lesson 33 +10 XP

Java Inheritance

Java Inheritance

Inheritance lets one class use the attributes and methods of another class. It helps you reuse code.

Superclass and subclass

  • The class that provides the members is the superclass (parent).
  • The class that inherits is the subclass (child).
  • Use extends to inherit.
class Vehicle {
  protected String brand = "Ford";

  public void honk() {
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";

  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.honk();
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

The Car object can use the honk() method and the brand attribute from Vehicle.

The protected modifier

protected makes a member visible in the same package and in subclasses, so Car can read brand.

Why use inheritance

  • Reuse code from a parent class.
  • Build new classes on top of existing ones.
  • Keep related classes consistent.

Important rule

Java supports single inheritance for classes: a class can extend only one superclass.

TL;DR

  • Use extends to inherit from a class.
  • The subclass gets the superclass methods and attributes.
  • protected members are visible to subclasses.