DEV Community

Sasireka
Sasireka

Posted on

Inheritance in Java

1) What is Inheritance?

Inheritance in Java is a core principle of Object-Oriented Programming (OOP) that allows a subclass (child) to acquire the properties (fields) and behaviors (methods) of a superclass (parent).

Syntax:

class ParentClass {
    // fields (variables)

    // methods
}

class ChildClass extends ParentClass {
    // additional fields

    // additional methods
}
Enter fullscreen mode Exit fullscreen mode

2) Types of Inheritance

Single Inheritance

One child class inherits from one parent class.

public class Animal {
    public void eat() {
        System.out.println("Eating");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("Barking");
    }
}
Enter fullscreen mode Exit fullscreen mode

Multilevel Inheritance

A class inherits from another class, which itself is inherited from another class.

public class Animal {
    public void eat() {
        System.out.println("Eating");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("Barking");
    }
}

public class Puppy extends Dog {
    public void weep() {
        System.out.println("Weeping");
    }
}
Enter fullscreen mode Exit fullscreen mode

Hierarchical Inheritance

Multiple child classes inherit from the same parent class.

public class Animal {
    public void eat() {
        System.out.println("Eating");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("Barking");
    }
}

public class Cat extends Animal {
    public void meow() {
        System.out.println("Meowing");
    }
}
Enter fullscreen mode Exit fullscreen mode

Multiple Inheritance (Not Supported with Classes)

A class cannot inherit from more than one class in Java.

But it is supported using interfaces (To be discussed)

Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance in a single program.

While Java does not support hybrid inheritance involving multiple classes (to avoid the "Diamond Problem"), it fully supports hybrid structures using interfaces. (To be discussed)

Top comments (0)