Hybrid inheritance in java with example and simple program – In hybrid inheritance, we use mixed of different types of inheritance relationship in java program.

For example, we can mix multilevel and hierarchical inheritance etc.

Prerequisite:

Before reading Hybrid inheritance in java language, you can read following different types of inheritance. Recommended to read simple Java inheritance example first.

Hybrid Inheritance Example

In below hybrid inheritance program example, multilevel and hierarchical inheritance both are mixed.

Multilevel ->

Son class inherits Father class, Father class inherits Grand Father class.

Daughter class inherits Father class, Father class inherits Grand Father class.

Hierarchical->

Son and Daughter both inherit Father class.

Above Multilevel and hierarchical statements are shown in below figure. Combination of both is shown as hybrid inheritance.

Hybrid inheritance in java

Hybrid Inheritance Code Example

/*
 * Hybrid inheritance java example
 */
//base

class GradFater {

	public void land() {
		System.out.println("GradFater's land");
	}

}

class Father extends GradFater {

	public void home() {
		System.out.println("Father's home");
	}

	public void Car() {
		System.out.println("Father's Car");
	}
}

// Inherit /derived / extends
class Son extends Father {

	// son constructor
	public Son() {
		System.out.println("Son...");
	}

	public void mobile() {
		System.out.println("Son's mobile");
	}
}

class Daughter extends Father {

	// Daughter constructor
	public Daughter() {
		System.out.println("Daughter...");
	}

	public void purse() {
		System.out.println("Daughter's purse");
	}
}

/*
 * Test hybrid inheritance
 */
public class TestHybridInheritance {

	public static void main(String[] args) {

		// Son object
		Son s = new Son();
		s.land();// Grand father method
		s.Car(); // Father method
		s.home();// Father method
		s.mobile();// son method

		// Daughter object
		Daughter d = new Daughter();
		d.land();// Grand father method
		d.Car(); // Father method
		d.home();// Father method
		d.purse();// son method

	}

}

Output:


Son…
GradFater’s land
Father’s Car
Father’s home
Son’s mobile
Daughter…
GradFater’s land
Father’s Car
Father’s home
Daughter’s purse

Related Posts