Multi level inheritance in java

Previous
Next

Multi-Level inheritance:

  • Accessing class members in more than one level of hierarchy.
  • Using child class object, it is possible to access the complete functionality of all the objects in the hierarchy.
/*class Object(consider as Grand Parent)
{
	int hashCode()
	{
		return object address in integer format.....
	}
}*/
class Parent // extends Object
{
	void m1()
	{
		System.out.println("Parent class functionality");
	}
}
class Child extends Parent
{
	void m2()
	{
		System.out.println("Child class functionality");
	}
}
class MultiLevelInheritance 
{
	public static void main(String[] args) 
	{
		Child obj = new Child();
		obj.m2();
		obj.m1();
		int address = obj.hashCode();
		System.out.println("Object address : "+address);
	}
}
  • In the process of Child object creation, JVM instantiates Parent class first because we need to extend (update) Child from Parent only.
  • As a programmer we can analyze whether the class is instantiating or not by defining a constructor.
  • In java application it is not possible to create object without calling constructor.
  • Hence Parent constructor invokes implicitly in the process of Child object creation.
class Parent
{
	Parent()
	{
		System.out.println("Parent's object creation");
	}
}
class Child extends Parent
{
	Child()
	{
		System.out.println("Child's object creation");
	}
}
class Check 
{
	public static void main(String[] args) 
	{
		new Child();
	}
}
  • JVM doesn’t allocate memory in different locations for different objects in the hierarchy.
  • The complete functionality of all the objects in the hierarchy can be accessed only by using only one object address (that is Child class).

Following program prints same address for both Parent and Child:

class Grand
{
	Grand()
	{
		System.out.println("Grand's : " + this);
	}
}
class Parent extends Grand
{
	Parent()
	{
		System.out.println("Parent's : " + this);
	}
}
class Child extends Parent
{
	Child()
	{
		System.out.println("Child's : " + this);
	}
}
class Check
{
	public static void main(String[] args) 
	{
		new Child();
	}
}

Output:
Grand's : Child@106d69c
Parent's : Child@106d69c
Child's : Child@106d69c
Previous
Next

Add Comment

Courses Enquiry Form