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:
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.