Inheritance in Java


☞The process by which some properties of a class are shared by another class or classes is known as inheritance.

☞It represents IS-A relationship which is also known as parent-child relationship.

Base class is a class that is inherited by another class

Derived class is one which inherits from a base class.

Base class is also known as Parent class, or Super class.
Base class is also known as Child class, or Target class, or Sub class.

Syntax :

class Derived_class extends Base_class{
    .......
}

Points to Remember

Private members of the base class cannot be accessed in the derived class.

Example

import java.util.*;

class Base_Class{
    private int a=50;
}

class Derive_Class extends Base_Class{
    
    int b=100;
    
    public static void main(String[] args) {
        Derived_Class obj = new Derived_Class();
        System.out.println("Value of a : "+obj.a);
        System.out.println("Value of b : "+obj.b);
    }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The field Base_Class.a is not visible

at Derived_Class.main(Derived_Class.java:9)

Public members of the base class can be accessed in the derived class.

Example

import java.util.*;

class Base_Class{
    public int a=50;
}

class Derive_Class extends Base_Class{
    
    int b=100;
    
    public static void main(String[] args) {
        Derived_Class obj = new Derived_Class();
        System.out.println("Value of a : "+obj.a);
        System.out.println("Value of b : "+obj.b);
    }
}

Output

Value of a : 50
Value of b : 100

Protected members of the base class can be accessed in the derived class.

Example

import java.util.*;

class Base_Class{
    protected int a=50;
}

class Derive_Class extends Base_Class{
    
    int b=100;
    
    public static void main(String[] args) {
        Derived_Class obj = new Derived_Class();
        System.out.println("Value of a : "+obj.a);
        System.out.println("Value of b : "+obj.b);
    }
}

Output

Value of a : 50
Value of b : 100

Types of Inheritance in Java

☞There are five types of inheritance in java.

1. Single Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance 
5. Hybrid Inheritance

Single Inheritance

☞If a single derived class inherits single base class, then it is known as Single Inheritance.



Multilevel Inheritance

☞If there is a chain of inheritance, then it is known as Multilevel Inheritance.



Hierarchical Inheritance

☞When two or more derived classes inherits a single base class, it is known as Hierarchical Inheritance.



Multiple Inheritance

☞When a derived class inherits more than one base class,it is known as Multiple Inheritance.



Hybrid Inheritance

☞When more than one type of inheritance systems are used together, it is known as Hybrid Inheritance.