Friday, September 11, 2020

Inheritance in Java

                                    Inheritance in Java

Inheritance is an important pillar of OOP(Object Oriented Programming).
Inheritance is the property of an object to acquire all its properties and behaviour of its parent object.

Syntax :

class derived-class extends base-class  
{  
   //methods and fields  
}  


Types:

1.single Inheritance
2.multilevel Inheritance
3.Hierarchical Inheritance

1. single Inheritance : single inheritance enables derived class to inherit properties and behaviour from a single parent class.



2.multilevel inheritance: multilevel inheritance enables derived class to inherit properties and behaviour from  parent class which is derived from another parent class.


 3.Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D.

4.Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple Inheritance with classes. In java, we can achieve multiple inheritance only through Interface. In image below, Class C is derived from interface A and B.






5.Hybrid Inheritance(Through Interfaces):
It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interface.






5 comments: