Google+

109. 'Inheritance' and the order of executing constructors






As we've already understood from our previous post that, as per Java the superclass constructor need to be executed first before directly executing the subclass constructor. To avoid this we've to use 'super' keyword to explicitly call the superclass constructor from the subclass constructor. So its very clear that superclass constructors are executed first before the subclass constructors.

If we don't mention super( ) in subclass constructor, by default the parameter less constructor in the superclass will get called. Java wont give error if parameter less constructor in the superclass exists, if not we have to explicitly call the constructor in the superclass using 'super' keyword.

Lets implement this on Eclipse IDE:

1. Create superclass 'ClassOne' containing Parameter less constructor as shown below and save:



2. Create subclass 'ClassTwo' containing Parameter less constructor as shown below and save:



3. Create subclass 'ClassThree' containing Parameter less constructor as shown below and save:



4. Create another class 'OrderOfExecutionDemo', which creates an object to call the parameter less constructor in subclass 'ClassThree' as shown below:



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



After looking at the output, its very clear that the statement inside the superclass constructor is executed first followed by its subclass constructors.

Download this project:

Click here to download the project containing the 'ClassOne', 'ClassTwo', 'ClassThree' and 'OrderOfExecutionDemo' 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.

'Method Overriding' will be explained in the next post.


No comments: