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 (1)

Collapse
 
shitij_bhatnagar_b6d1be72 profile image
Shitij Bhatnagar

Thanks for writing.

Few suggestions:
1) You could also show overriding of functions i.e. @override annotation
2) You could add another example of dynamic polymorphism e.g. Parent parentRef = new Child();
3) Another practical use of inheritance is in creating abstract parent classes and giving it some methods; and then child classes can expand on those