Labs ICT
โญ Pro Login

Inheritance

Imagine you have a Vehicle class with fields like speed and methods like move(). Now you want to create a Car class and a Bike class. Do you rewrite all that code? Of course not.

Inheritance lets one class borrow the fields and methods of another class. You write the common stuff once, and then each subclass adds its own special behavior.

The extends Keyword

You use the extends keyword to make a class inherit from another class. The class being inherited from is the superclass (or parent), and the class that inherits is the subclass (or child).

class Vehicle {
  int speed = 0;

  void move() {
    System.out.println("Moving...");
  }
}

class Car extends Vehicle {
  String brand = "Toyota";
}

public class Main {
  public static void main(String[] args) {
    Car c = new Car();
    System.out.println(c.brand);
    System.out.println(c.speed);
    c.move();
  }
}

Car only defined brand, but it also has speed and move() because it inherited them from Vehicle. That is the power of inheritance.

Using super()

When a subclass constructor runs, it can call the superclass constructor using super(). This lets you pass values up to the parent class.

class Vehicle {
  int speed;

  Vehicle(int speed) {
    this.speed = speed;
  }
}

class Car extends Vehicle {
  String brand;

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

The super(speed) call goes to Vehicle(int speed) and sets the speed. Then the Car constructor handles its own brand field. You have to put super() as the very first line in the constructor.

Method Overriding

Sometimes the parent's method is too generic. A Vehicle might move() one way, but a Car needs to move differently. That is where method overriding comes in โ€” you redefine the method in the subclass.

class Vehicle {
  void move() {
    System.out.println("Vehicle is moving");
  }
}

class Car extends Vehicle {
  void move() {
    System.out.println("Car is driving on the road");
  }
}

public class Main {
  public static void main(String[] args) {
    Car c = new Car();
    c.move();
  }
}

The Car version of move() runs instead of the Vehicle version. The method signature must be exactly the same โ€” same name, same parameters, same return type. That is how Java knows you are overriding and not accidentally overloading.

๐Ÿงช Quick Quiz

What does super() do in a constructor?