Loading

       Types of Inheritance

There are mainly three types of inheritance in java:

  • Single Level Inheritance
  • Multi-Level Inheritance
  • Hierarchical Inheritance

Note: There is one more type of inheritance known as multiple inheritances although not supported by classes but can be used in interfaces


1. Single-Level Inheritance:-


Example:

package quipohouse;
class Parent {
	int a = 10;

	void parentMethod() {
		System.out.println("Inside Parent Class");
	}
}

class Child extends Parent {
	int b = 20;

	void child1Method() {
		System.out.println("Inside Child Class");
	}

	public static void main(String[] args) {
		Child c = new Child();
		c.child1Method();
		c.parentMethod();
		System.out.println("Child class field:" + c.b);
		System.out.println("Parent class field:" + c.a);
	}
}

Output:

Inside Child Class
Inside Parent Class
Child class field:20
Parent class field:10

2. Multi-Level Inheritance:-


Example:

package quipohouse;
class Parent {
	int a = 10;

	void parentMethod() {
		System.out.println("Inside Parent Class");
	}
}

class Child1 extends Parent {
	int b = 20;

	void child1Method() {
		System.out.println("Inside Child1 Class");
	}
}

class Child2 extends Child1 {
	int c = 30;

	void child2Method() {
		System.out.println("Inside Child2 Class");
	}

	public static void main(String[] args) {
		Child2 c = new Child2();
		c.parentMethod();
		c.child1Method();
		c.child2Method();
		System.out.println("Parent Class Field:" + c.a);
		System.out.println("Child1 Class Field:" + c.b);
		System.out.println("Child2 Class Field:" + c.c);

	}
}

Output:

Inside Parent Class
Inside Child1 Class
Inside Child2 Class
Parent Class Field:10
Child1 Class Field:20
Child2 Class Field:30

3. Hierarchical Inheritance:-


Example:

package quipohouse;
class Parent {
	int a = 10;

	void parentMethod() {
		System.out.println("Inside Parent Class");
	}
}

class Child1 extends Parent {
	int b = 20;

	void child1Method() {
		System.out.println("Inside Child1 Class");
	}
}

class Child2 extends Parent {
	int c = 30;

	void child2Method() {
		System.out.println("Inside Child2 Class");
	}

	public static void main(String[] args) {
		Child1 c1 = new Child1();
		Child2 c2 = new Child2();
		c1.parentMethod();
		c2.parentMethod();
		System.out.println("Parent class field accessed by Child1 class:" + c1.a);
		System.out.println("Parent class field accessed by Child2 class:" + c2.a);
	}
}

Output:

Inside Parent Class
Inside Parent Class
Parent class field accessed by Child1 class:10
Parent class field accessed by Child2 class:10