Thuta Learning
AdvancedProgrammingbeginner

Inheritance

Relax. We'll talk through this in plain words — no textbook voice.

Inheritance is when one class inherits the fields/methods of another class. The parent class is called the superclass, and the child class is called the subclass. extends keyword. It's used for code reuse and for grouping common behavior together in the parent class.

java
class Vehicle {
  protected String brand = "Ford";

  void start() {
    System.out.println("Vehicle is starting...");
  }
}

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

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

Car class extends Vehicle, so it can use the brand field and the start() method from Vehicle.

You should see
Vehicle is starting... Ford Mustang

Real-World Use

The inheritance pattern fits relationships like AdminUser/User, Car/Vehicle, Dog/Animal, or PremiumPlan/Plan.

Easy traps

  • Child classes can't access private fields directly. Use protected or a getter method when you need that access.
Inheritance | Thuta Learning