Hybrid inheritance is a type of inheritance in which two or more variations of inheritance are used. For instance, suppose, there are various classes namely A, B, C, D and E. if class A gets extended by class B, then this would be an example of Single inheritance. Further, if class C, D and E extend class B,then it would be an example of hierarchical inheritance. In this manner, multiple types of inheritance can be used within the same hierarchy structure, that is termed Hybrid inheritance.
Hybrid inheritance can be implemented using combination of single, multilevel, and hierarchical inheritance. Below is a simple example for the same.
Program:
public class A { public void display() { System.out.println("I am a method from class A"); } } class B extends A { public void print() { System.out.println("I am a method from class B"); } } class C extends B{ public void show() { System.out.println("I am a method from class C"); } } class D extends B{ public void show() { System.out.println("I am a method from class D"); } } class E extends B { public void outPut() { System.out.println("I am a method from class E"); } public static void main(String[] args) { E objE = new E(); objE.display(); // A is indirect parent of E, therefore, the display method gets inherited all the way to leaf } }
Output:
I am a method from class A
Explanation:
Program:
public class A { public void display() { System.out.println("I am a method from class A"); } } class B extends A { public void print() { System.out.println("I am a method from class B"); } } class C extends B { public void show() { System.out.println("I am a method from class C"); } } class D extends C { public void show() { System.out.println("I am a method from class D"); } } class E extends C { public void outPut() { System.out.println("I am a method from class E"); } public static void main(String[] args) { E objE = new E(); objE.display(); // A is indirect parent of E, therefore, the display method gets inherited all the way to leaf } }
Output:
I am a method from class A
Explanation:
This post was last modified on October 28, 2022