DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

Java Inheritance

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • subclass (child) - the class that inherits from another class
  • superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

  • Superclass (Parent): The class whose features are inherited
  • Subclass (Child): The class that inherits features
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();    // inherited method
        obj.display(); // own method
    }
}
Enter fullscreen mode Exit fullscreen mode

Types of Inheritance in Java

Java supports these types:

1. Single Inheritance

One class inherits from one class

class A {}
class B extends A {}
Enter fullscreen mode Exit fullscreen mode

2. Multilevel Inheritance

A chain of inheritance

class A {}
class B extends A {}
class C extends B {}
Enter fullscreen mode Exit fullscreen mode

3. Hierarchical Inheritance

Multiple classes inherit from one parent

class A {}
class B extends A {}
class C extends A {}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)