DEV Community

Chandru
Chandru

Posted on

Java Inheritance: Reusing Code Made Simple

Inheritance is one of the important concepts of Object-Oriented Programming (OOP) in Java.

It allows one class to acquire the properties and methods of another class. This helps us reuse code and avoid unnecessary duplication.

What is Inheritance?

Inheritance allows a child class to inherit variables and methods from a parent class.

Java uses the extends keyword to implement inheritance.

Simple Example

class Animal {

    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {

    void bark() {
        System.out.println("Dog is barking");
    }
}

public class Main {

    public static void main(String[] args) {

        Dog dog = new Dog();

        dog.eat();
        dog.bark();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Animal is eating
Dog is barking
Enter fullscreen mode Exit fullscreen mode

Here:

  • Animal is the parent class.
  • Dog is the child class.
  • extends allows Dog to inherit from Animal.
  • The Dog object can access both eat() and bark().

Types of Inheritance in Java

Java supports these inheritance types with classes:

  1. Single Inheritance – One child class inherits from one parent class.
  2. Multilevel Inheritance – A class inherits from a child class, forming a chain.
  3. Hierarchical Inheritance – Multiple child classes inherit from one parent class.

Java does not support multiple inheritance through classes, but similar functionality can be achieved using interfaces.

Why Use Inheritance?

  • Code reusability
  • Reduces code duplication
  • Easier code maintenance
  • Supports method overriding
  • Helps build relationships between classes

Top comments (0)