Inheritance in Java

0 Comments
Source

Inheritance is a concept in which one object interacts with the other object, where the properties of one class can be inherited by another class. It helps developer or programmer to reuse code and create a new bond between classes.

Two things are involved in this process;

  • Parent class (Base or Super class)
  • Child class (Subclass class)

A class that inherits the properties is Child class on the other hand a class whose properties are inherited is known as Parent class

Inheritance is further classified into 4 types:

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Extends keyword is used if a class wants to inherit properties of some other class

Single Inheritance:

Class A

{

// code

}

Class B extends A

{

// code

}

This is an example of Single Inheritance in which one class i.e Child class extends the properties of Parent class

Multilevel Inheritance:

Class A

{

// code

}

Class B extends A

{

// code

}

Class C extends B

{

// code

}

This is an example of Multilevel Inheritance when a class is derived from another a class which is also derived from other class. A relationship in which there is more than one parent class but at different levels this type of relationship is Multilevel Inheritance.

Hierarchical Inheritance:

Class A

{

// code

}

Class B extends A

{

// code

}

Class C extends A

{

// code

}

This is an example of Hierarchical Inheritance when a class is derived from more than one classes. Which means there is more than one child classes of a Parent class.

Hybrid inheritance:

Multiple inheritance is not supported in Java as it leads to ambiguity, so this type of inheritance can only be achieved through the use of the interfaces.

If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B and C are the parent class of D which is the only child class of B and C.


Leave a Reply

Your email address will not be published.