Google+

Like Us On Facebook


Total Pageviews

108. Explicitly invoke Super class constructors






Suppose you have a subclass under a superclass and both the superclass and subclass contain constructors.You have only called the constructor of subclass from a different class. Will this work?

The answer is No. Since the superclass has no knowledge of its subclass, and if you think logically it makes sense that the possible prerequisites to be performed in superclass constructor before executing the  constructor in the subclass, the Java has kept a rule of executing the constructor in the superclass first before  directly executing the subclass constructor. Hence we've to explicitly invoke/call the  Superclass constructor using  the 'super' keyword, so that constructor in the superclass is executed first.

Lets implement this on Eclipse IDE by first finding out what happens when both the superclass and subclass have their own constructors, constructor in the subclass is called directly without explicitly invoking the constructor in superclass using 'super' keyword:

1.Create a superclass 'Superclass' containing a constructor as shown below and save:



2. Create subclass 'Subclass' containing a constructor and this constructor is not using 'super' keyword to explicitly invoke the constructor in superclass 'Superclass' as shown below and save:



3. View the error displayed in  the subclass for not explicitly calling the constructor in superclass as shown below:



4. Lets fix this error by explicitly calling the superclass constructor using the 'super' keyword as shown below and save:



5. Observe that the error got resolved

Download this project:

Click here to download the project containing 'Superclass' and 'Subclass' 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.

'Inheritance' and order of executing constructors will be explained in the next post.



1 comment:

Vijaykumar Mohith said...
This comment has been removed by the author.

Blog Index