Types of Inheritance


There are 3 types of inheritance in java:

1. Single

2. Multilevel

3. Hierarchical

Note: In java programming, multiple and hybrid inheritance is only supported through interface and not through classes.


Single Inheritance


Single Inheritance means a class is extended/inherited from only one other class.

Syntax:

class A{
}

class B extends A{
}

Example:

class Father
{
    void profession()
    {
        System.out.println("Teacher...");
    }
}

class Children extends Father
{  
    void hobby()
    {
        System.out.println("Playing...");
    }
}  

class SingleInheritance
{
    public static void main(String args[])
    {
        Children c=new Children();  
        c.profession();  
        c.hobby();  
    }
}

Output:

Teaching...
Playing...

Multilevel Inheritance


In multilevel inheritance, a class is extended/inherited from a derived class, hence making this derived class the base class for the new class.

Syntax:

class A{
}

class B extends A{
}

class C extends B{
}

Example:

class GrandFather
{
    void age1()
    {
        System.out.println("GrandFather is 67 years old.");
    }
}

class Father extends GrandFather
{
    void age2()
    {
        System.out.println("Father is 44 years old.");
    }
}

class Children extends Father
{
    void age3()
    {
        System.out.println("Children is 20 years old.");
    }
}

class MultilevelInheritance
{
    public static void main(String args[])
    {
        Children c=new Children();  
        c.age1();  
        c.age2();
        c.age3();
    }
}

Output:

GrandFather is 67 years old.
Father is 44 years old.
Children is 20 years old.

Hierarchical Inheritance


In hierarchical inheritance, many sub-classes are inherited from the common parent or base class.

Syntax:

class A{
}

class B extends A{
}

class C extends A{
}

Example:

class Father
{
    void profession()
    {
        System.out.println("Father’s profession is Teaching.");
    }
}

class Son extends Father
{
    void game()
    {
        System.out.println("Son plays football.");
    }  
}

class Daughter extends Father
{  
    void hobby()
    {
        System.out.println("daughter’s hobby is dancing.");
    }
}

class HybridInheritance
{
    public static void main(String args[])
    {
        Son s=new Son();
        Daughter d=new Daughter();
        s.profession();
        s.game();
        d.profession();
        d.hobby();
    }
}

Output:

Father’s profession is Teaching.
Son plays football.
Father’s profession is Teaching.
daughter’s hobby is dancing.