Inheritance

Inheritance is a mechanism in Java by which one class can inherit the properties and methods of another class.

How Inheritance Works

Inheritance is implemented using the extends keyword:


public class Vehicle {
    String brand;
    
    public void honk() {
        System.out.println("Beep beep!");
    }
}

public class Car extends Vehicle {
    String model;
    
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.brand = "Toyota";
        myCar.model = "Corolla";
        myCar.honk();
        System.out.println(myCar.brand + " " + myCar.model);
    }
}
      

In this example, Car is a subclass of Vehicle, inheriting its properties and methods.

Types of Inheritance

Java supports the following types of inheritance:

  • Single Inheritance – A class inherits from one superclass.
  • Multilevel Inheritance – A class inherits from a superclass, and another class inherits from that subclass.
  • Hierarchical Inheritance – Multiple classes inherit from a single superclass.

Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method already provided by its superclass:


public class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
    
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.makeSound(); // Outputs: Bark
    }
}
      

In this example, the Dog class overrides the makeSound method of the Animal class.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top