0
Explore
0

Inheritance in Java – A Complete Guide

Updated on July 28, 2025

Inheritance is one of the most powerful features of Object-Oriented Programming (OOP), and Java fully supports it. It allows a new class (called a subclass or child class) to inherit the properties and behaviors (fields and methods) of an existing class (called a superclass or parent class).

In simple terms, inheritance enables code reusability and establishes a natural hierarchical relationship between classes. For example, if you have a general class Animal, you can create specific child classes like Dog, Cat, or Bird that inherit from it. These child classes can reuse common functionality from Animal, while also adding their own unique features.

Understanding inheritance is crucial because it’s the foundation for more advanced OOP concepts like polymorphism, method overriding, and runtime behavior customization. In this tutorial, we’ll learn everything you need to know about inheritance in Java – from basic syntax to real-world examples and best practices.

What is Inheritance?

Imagine your family: you inherit traits like eye color or height from your parents. Similarly, in Java, inheritance allows one class (child) to inherit the properties and behavior (fields and methods) of another class (parent).

Inheritance is a core concept of Object-Oriented Programming (OOP), and Java supports it extensively to promote code reusability, method overriding, and hierarchical classification.

Syntax of Inheritance

class Parent {
    // properties and methods
}

class Child extends Parent {
    // additional properties and methods
}

Here, Child class inherits from Parent class using the extends keyword.

Java Inheritance Example

class Employee {
    String name = "John Doe";
    double salary = 50000;

    void showDetails() {
        System.out.println("Employee Name: " + name);
        System.out.println("Base Salary: $" + salary);
    }
}

class Manager extends Employee {
    double bonus = 15000;

    void showManagerDetails() {
        showDetails(); // Call parent method
        System.out.println("Manager Bonus: $" + bonus);
        System.out.println("Total Salary: $" + (salary + bonus));
    }
}

public class Main {
    public static void main(String[] args) {
        Manager m1 = new Manager();
        m1.showManagerDetails(); // Access both Employee and Manager data
    }
}

Output

Employee Name: John Doe
Base Salary: $50000.0
Manager Bonus: $15000.0
Total Salary: $65000.0

Explanation:

  1. Employee class is the parent (superclass).
    • It contains fields name and salary.
    • The method showDetails() prints basic employee info.
  2. Manager class is the child (subclass) that inherits from Employee.
    • It adds its own field bonus.
    • The method showManagerDetails() prints manager info and total salary using both inherited and own properties.
  3. In the main() method, we create an object of Manager class.
    • Since Manager inherits from Employee, it has access to all its fields and methods.
    • The program shows how inheritance allows reuse and extension of existing class functionality.

Why Use Inheritance?

Here’s why inheritance is so useful in Java:

Code Reusability: Write once, use in multiple classes.
Method Overriding: Child class can change behavior of parent class methods.
Code Organization: Organize related classes into a hierarchy.
Polymorphism: Enables dynamic method invocation and flexibility in code design.

Types of Inheritance in Java

Java supports

  1. single Inheritance
  2. multilevel Inheritance
  3. hierarchical inheritance.

Note: Java does not support Multiple Inheritance with classes to avoid ambiguity, but it supports it with interfaces.

1. Single Inheritance

In single inheritance, a class (subclass or child class) inherits from only one superclass (parent class). The child class gets access to all the non-private members (like methods and variables) of the parent class. This allows for code reusability and a clear hierarchical relationship between classes.

In short, A class inherits from one superclass.

Real-World Analogy:

Think of it like this:
A Dog is an Animal. So, a Dog should naturally have the behaviors of an Animal (like eating), but it can also have its own specific behavior (like barking).
This is exactly what single inheritance models in Java.

Example – Single Inheritance

class Animal {
    String category = "Mammal";

    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    String breed = "Labrador";

    void bark() {
        System.out.println("Dog barks loudly.");
    }

    void showDetails() {
        System.out.println("Category: " + category);  // Inherited variable
        System.out.println("Breed: " + breed);        // Own variable
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog1 = new Dog();
        dog1.eat();         // Inherited method from Animal
        dog1.bark();        // Method in Dog
        dog1.showDetails(); // Mix of inherited and own data
    }
}

Output:

This animal eats food.
Dog barks loudly.
Category: Mammal
Breed: Labrador

Step-by-Step Explanation:

  1. Animal Class (Parent)
    • Field: category
    • Method: eat()
    • Represents a general animal behavior.
  2. Dog Class (Child)
    • Inherits everything from Animal.
    • Adds its own field breed and methods bark() and showDetails().
  3. Inheritance in Action:
    • dog1.eat() → Calls the eat() method from Animal.
    • dog1.bark() → Calls its own method.
    • dog1.showDetails() → Shows use of both inherited and own variables.

2. Multilevel Inheritance

Multilevel inheritance means a class inherits from another class, which in turn inherits from another class.
It creates a chain of inheritance, where properties and methods are passed down through multiple levels.

In short we can say it as A class inherits from a class that inherits from another class.

Real-World Analogy:

Imagine a Puppy is a type of Dog, and a Dog is an Animal.
So, a Puppy should have the behaviors of both a Dog and an Animal.

Example – Multilevel Inheritance

class Animal {
    String type = "Living Being";

    void eat() {
        System.out.println("Animal eats food.");
    }
}

class Dog extends Animal {
    String breed = "German Shepherd";

    void bark() {
        System.out.println("Dog barks loudly.");
    }
}

class Puppy extends Dog {
    int ageInMonths = 3;

    void weep() {
        System.out.println("Puppy weeps softly.");
    }

    void showInfo() {
        System.out.println("Type: " + type);          // From Animal
        System.out.println("Breed: " + breed);        // From Dog
        System.out.println("Age: " + ageInMonths + " months"); // Own
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();       // Inherited from Animal
        p.bark();      // Inherited from Dog
        p.weep();      // Defined in Puppy
        p.showInfo();  // Shows combined details
    }
}

Output

Animal eats food.
Dog barks loudly.
Puppy weeps softly.
Type: Living Being
Breed: German Shepherd
Age: 3 months

Step-by-Step Explanation:

  1. Class Animal (Base Class)
    • Field: type
    • Method: eat()
  2. Class Dog (Inherits from Animal)
    • Field: breed
    • Method: bark()
  3. Class Puppy (Inherits from Dog)
    • Field: ageInMonths
    • Methods: weep() and showInfo()
  4. How Multilevel Inheritance Works Here
    • Puppy inherits all public and protected fields and methods from both Dog and Animal.
    • It can directly access eat() and bark() without redefining them.
    • It also defines its own behavior using weep() and showInfo().

3. Hierarchical Inheritance

In hierarchical inheritance, multiple subclasses inherit from a single superclass.
Each subclass gets access to the fields and methods of the parent class but can also have its own unique behavior.

In Short, Multiple classes inherit from a single superclass.

Real-World Analogy:

Think of Animal as a general category. From it, we can derive specific types like Dog and Cat.
Both are animals and share common features (like eating), but each has its own behavior (barking or meowing).

Example – Hierarchical Inheritance

class Animal {
    String type = "Domestic";

    void eat() {
        System.out.println("Animal eats food.");
    }
}

class Dog extends Animal {
    String breed = "Beagle";

    void bark() {
        System.out.println("Dog barks: Woof Woof!");
    }

    void showDogDetails() {
        System.out.println("Type: " + type);   // Inherited
        System.out.println("Breed: " + breed); // Own field
    }
}

class Cat extends Animal {
    String color = "White";

    void meow() {
        System.out.println("Cat meows: Meow Meow!");
    }

    void showCatDetails() {
        System.out.println("Type: " + type);   // Inherited
        System.out.println("Color: " + color); // Own field
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();              // Inherited from Animal
        dog.bark();             // Own method
        dog.showDogDetails();   // Combined info

        System.out.println();

        Cat cat = new Cat();
        cat.eat();              // Inherited from Animal
        cat.meow();             // Own method
        cat.showCatDetails();   // Combined info
    }
}

Output:

Animal eats food.
Dog barks: Woof Woof!
Type: Domestic
Breed: Beagle

Animal eats food.
Cat meows: Meow Meow!
Type: Domestic
Color: White

Step-by-Step Explanation:

  1. Animal (Superclass)
    • Common field: type
    • Common method: eat()
  2. Dog (Subclass of Animal)
    • Adds field breed
    • Adds method bark() and showDogDetails()
  3. Cat (Subclass of Animal)
    • Adds field color
    • Adds method meow() and showCatDetails()
  4. Main Class
    • Creates one object of Dog and one of Cat
    • Both call the inherited eat() method
    • Each shows its unique behavior and details

4. Multiple Inheritance (Not Supported with Classes)

Java doesn’t support multiple inheritance with classes to avoid ambiguity (diamond problem). But it does support multiple inheritance using interfaces.

Key Concepts in Inheritance

The super Keyword

Used to refer to the immediate parent class. It helps to:

  • Call parent class constructor
  • Access parent class methods or fields
class Animal {
    Animal() {
        System.out.println("Animal constructor called");
    }
}

class Dog extends Animal {
    Dog() {
        super(); // calls Animal constructor
        System.out.println("Dog constructor called");
    }
}

Method Overriding

The child class redefines a method of the parent class with the same name, return type, and parameters.

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

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

final Keyword

If you don’t want a method to be overridden or a class to be extended, use final.

final class Animal {
    // Cannot be extended
}

class Dog extends Animal {  // ❌ Compile-time Error
}

Constructor Behavior in Inheritance

When an object of a subclass is created, the constructor of the parent class is called first, then the subclass constructor.

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Child Constructor");
    }
}

Output:

Parent Constructor  
Child Constructor

Quick Recap: Inheritance Concepts Table

FeatureDescription
extendsKeyword used to inherit a class
superAccess parent constructor or members
Method OverridingRedefine method in child class
final keywordPrevent overriding or inheritance
Code ReusabilityMajor benefit of inheritance
Constructor ChainingParent constructor runs before child’s

Practice Questions

  1. What is the purpose of inheritance in Java?
  2. Write a program with multilevel inheritance showing Vehicle -> Car -> SportsCar.
  3. What will happen if you override a method without using @Override?
  4. Can constructors be inherited? Why or why not?
  5. Explain the diamond problem and how Java avoids it.

💡 Final Thoughts

Inheritance is a powerful mechanism that makes your Java programs modular, flexible, and efficient. It reflects real-world relationships and encourages code reuse. Mastering inheritance also helps in grasping more advanced topics like polymorphism, abstraction, and interfaces.L;KCG8

❓ Frequently Asked Questions (FAQ) – Inheritance in Java

1️⃣ What is inheritance in Java?

Inheritance is an object-oriented programming feature in Java that allows a class to acquire the properties and behaviors (fields and methods) of another class. It helps in code reuse and establishing a parent-child relationship between classes.

2️⃣ What keyword is used to inherit a class in Java?

Java uses the extends keyword to inherit one class from another.

Example:

class Dog extends Animal { }

3️⃣ Can a class inherit more than one class in Java?

No, Java does not support multiple inheritance with classes due to the diamond problem. However, it can implement multiple interfaces.

4️⃣ Are constructors inherited in Java?

No, constructors are not inherited. However, a subclass can call a superclass constructor using the super() keyword.

5️⃣ What are the types of inheritance in Java?

Java supports the following types of inheritance:

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

Java does not support multiple or hybrid inheritance with classes, but it supports multiple inheritance through interfaces.

6️⃣ Can private members of a superclass be inherited?

No, private members of a superclass are not accessible directly in the subclass. But they are technically inherited and can be accessed using public/protected getters and setters.

7️⃣ What is the difference between super and this in Java?

  • super refers to the immediate parent class.
  • this refers to the current class instance.
    Example:
super.eat(); // Calls parent method  
this.eat();  // Calls current class method

8️⃣ What is method overriding in inheritance?

Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its superclass. It enables runtime polymorphism.

9️⃣ Can a final class be inherited?

No, a class declared as final cannot be extended. This is used to prevent inheritance.
Example:

final class Vehicle { } // Cannot be extended by any other class

🔟 Why is inheritance important in Java?

Inheritance promotes:

  • Code reusability
  • Logical hierarchy
  • Better organization of code
  • It also supports polymorphism, making it easier to write flexible and maintainable applications.