Super keyword is used to access any variable or method or constructor of the immediate parent class in java. So it is a keyword used in inheriatance whenever we want to call a variable, method or constructor in java.
Below is an example that shows how super keyword works.
Example (comparision with this keyword):
In this block of code I've made two classes, a parent class and a child class that extends parent class to perform inheritance.And I made a variable named strength in each class and then I made a method showStrength() to display strengths of both the class.
Now both the variables have same name so if I was to directly call strength the compiler would not know the variable of which of the class is being called, so like we use this keyword to signify that the particular object is being called, we use super keyword to signify that the part of the immediate parent class it to be called.
Output:
So I used this and super keyword together to show the similarity and differences in both of them.
Now below is an example that shows that every constructor has an inbuilt super keyword that is present though it is not visible.
Super in constructor:
In this code again I used the parent and child class but this time I also made a default constructor of each class which would be directly called whenever an object of any of the classes is created.
Then I made an object of the child class only. But when we look at the output the constructor of both the classes have been run. Check the output below for understanding.
Output:
This happened because each constructor has a default inbuilt super keyword mentioned, that executes the constructor of its immediate parent class automatically.
To show the working of the super keyword I've commented super for understanding in each constructor, that even though we do not write it in the code it is automatically present there.
Top comments (0)