Google+

105. Calling 'Superclass' constructors using 'super' keyword






A subclass can call a constructor defined by its superclass using the 'super' keyword.

Example:   super(10,10,10);  kind of statement should be written in subclass to call the constructor having three parameters in superclass

Lets implement this on Eclipse IDE:

1.Create 'Superclass' superclass as shown below:



2. Create 'Subclass' subclass calling a constructor created in 'Superclass' using the 'super' keyword as shown  below:



3. Create 'SuperCallingConstructor' class which creates an object for 'Subclass' and calls the constructor created in 'Subclass' by passing few values during object creation itself as shown below:



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



Download this project:

Click here to download this project containing 'Superclass', 'Subclass' and 'SuperCallingConstructor' class files used in this post (You can download this project and import into Eclipse IDE on your machine)

We can also use:
  • super(object) to pass objects while calling the constructor in superclass.
  • super( ) to pass nothing while calling the constructor in superclass.





Please comment below to feedback or ask questions.

'Multilevel Hierarchy' will be explained in the next post.


No comments: