
Inheritance in Java
Inheritance in Java
Inheritance is the mechanism where a class can acquire the fields or the behaviors of another class. By this we can reduce the code redundancy by inheriting the existing methods to the child classes. A keyword extends is used while inheriting class.
The class which is inheriting the properties is called as “sub class” or “child class”.
The class from which sub class is inheriting the properties is called as “super class” or “parent class”.
Example:
class SuperClass{ public void supermethod(){ System.out.println(“super class Method”); } } class SubClass extends SuperClass{ public void submethod(){ System.out.println(“sub class Method”); } } class MainClass{ public static void main(String[] args){ SubClass objSubClass = new SubClass(); objSubClass.submethod(); objSubClass.supermethod(); } } |
Types of Inheritance:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance
- Hybrid Inheritance
Single Inheritance:
If sub class is inheriting properties from one class that is called as single inheritance.
Example:
class Animal{public void eating(){ System.out.println(“animal class eating method”); } } class Tiger extends Animal{ public void roaring(){ System.out.println(“tiger class roaring method”); } } |
Multilevel Inheritance:
When the sub class(B) which has been inherited from a super class(A) acts as sub class for another class(C) it such relation is multilevel inheritance.
Example:
class A{public void eating(){ System.out.println(“animal class eating method”); } } class B extends A{ public void roaring(){ System.out.println(“tiger class roaring method”); } } class C extends B{ public void roaring(){ System.out.println(“tiger class roaring method”); } } |
Hierarchical Inheritance :
When single class(A) is inherited by multiple class(B,C,D) then it is called as Hierarchical Inheritance.
Example:
class A{ public void eating(){ System.out.println(“animal class eating method”); } } class B extends A{ public void roaring(){ System.out.println(“tiger class roaring method”); } } class C extends A{ public void roaring(){ System.out.println(“tiger class roaring method”); } } class D extends A{ public void roaring(){ System.out.println(“tiger class roaring method”); } } |
Multiple Inheritance :
When multiple class(A,B) is been inherited by single class(C) it is called as multiple inheritance.
Note : Multiple inheritance is not supported by classes because when class A and B has same method then by using C class reference when we call that method then there will be ambiguity problem. But multiple inheritance is supported in interfaces by abstract methods.
Hybrid Inheritance:
It is combination of multilevel and multiple inheritance. As multiple inheritance is not supported by classes so hybrid inheritance is not applicable for classes.