DEV Community

Saravanan s
Saravanan s

Posted on

Inheritance in Java

Inheritance in Java

Inheritance is one of the most important features of Object-Oriented Programming (OOP) in Java. It allows one class to acquire the properties and behaviors of another class. This helps in code reuse, better organization, and easier maintenance.

What is Inheritance?

Inheritance is a mechanism where a child class (subclass) inherits variables and methods from a parent class (superclass).

Why Use Inheritance?

Inheritance provides many benefits:

Code Reusability – Write code once and use it multiple times

Method Overriding – Achieve runtime polymorphism

Improved Maintainability – Changes in parent class reflect in child class

class Parent {
    void show() {
        System.out.println("This is parent class");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("This is child class");
    }
}

public class Main {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.show();
        obj.display();
    }
}

Enter fullscreen mode Exit fullscreen mode

output

This is parent class
This is child class

Enter fullscreen mode Exit fullscreen mode

Top comments (0)