Google+

107. Using 'super' in Multilevel Hierarchy







From the previous post, we already know that one of use of the 'super' keyword is to call the constructors in the superclass. Now lets use the 'super' keyword to access the constructors in superclasses in multilevel hierarchy.

But 'super' keyword used in the subclass can only call the constructor in its immediate superclass. It cant call the constructor in the superclass of its superclass. If A is super class of B and B is superclass of C. Then 'super' keyword in 'C' class can only call the constructor of its superclass 'B' class but cant call the constructor of superclass of its superclass i.e. 'A' class.

Lets implement this in Eclipse IDE:

1. Create superclass 'ClassOne' as shown below:



2. Create subclass 'ClassTwo' for superclass 'ClassOne' and the 'super' keyword used in this subclass will call the constructor created in the superclass as shown below:



3. Create subclass 'ClassThree' for superclass 'ClassTwo' and the 'super' keyword used in this subclass will call the constructor created in its immediate superclass 'ClassTwo' and won't call the constructor created in the next level superclass 'ClassOne' as shown below:



4. Create another class 'SuperLevelDemo' to create an object for subclass 'ClassThree' , the create object calls the constructor in subclass 'ClassThree' by default:



5. Save and Run the 'SuperLevelDemo' class
6. Observe that the output is displayed in the console as shown below:



Download this project:

Click here to download the project containing 'ClassOne', 'ClassTwo', 'ClassThree' and 'SuperLevelDemo' class files used in this post (You can download this project and import into Eclipse IDE on your machine)



Please comment below to feedback or ask questions.

'Explicitly Invoke Super class constructor'  will be explained in the next post.




1 comment:

Mani said...

Hi Arun,

Thanks a lot for your detailed tutorials. Its really helpful for me.

I am running the above "SuperLevelDemo" , but commented the Class Two Super( ).. but still getting same result.

how?

-------

public class ClassThree extends ClassTwo
{

//Create constructor to call the constructor in its immediate superclass 'ClassTwo' and print text inside the constructor of this class
//'super' keyword here wont call the constructor created in its next level superclass 'ClassOne'
ClassThree()
{
//super();//This method call will call the constructor created in its super class 'ClassTwo' and wont call the constructor in 'ClassOne'

System.out.println("This is the Text inside the constructor in ClassThree");

}


}
---------------
output:

This is the Text inside the constructor in ClassOne
This is the Text inside the constructor in ClassTwo
This is the Text inside the constructor in ClassThree

Blog Index