Super keyword in Java

Super keyword in Java is used to refer to the immediate parent class of the sub class.

You can use super keyword in Java in following ways-

  • You can invoke the constructor of the parent class, doing that using super makes your code more compact and classes are better encapsulated. We’ll see an example soon.
  • You can also use super keyword to access the field or method of the parent class that has been hidden by the child class.

Using super to invoke constructor of super class

To see how super keyword in Java can be used to invoke constructor of the immediate parent class and how it helps in reducing duplication of code and helps with better encapsulation first let’s see a code where super is not used.

Output

In the code class B extends class A. If you notice the constructor of class B again initializes the fields it inherits from class A (x and y). Same initialization is also done in constructor of class A leading to duplication of code.

Another problem here is the fields in class A can’t be marked as private as the fields have to be accessed in the child class B that means class A is not properly encapsulated.

Using super keyword
Let’s see the same example again when super keyword is used to invoke the constructor of the parent class.

In the code you can see that the super is used to invoke the constructor of the parent class which initializes the fields in parent class. That way, x and y fields can be marked as private so class A has better encapsulation. Also the same initialization is not needed in constructor of class B so no duplication of code.

Note that call to super() must be the first statement in the subclass constructor otherwise there will be a compilation error “Constructor call must be the first statement in a constructor”.

Using super to access the field and method of the parent class

Another use of super keyword in Java is to access the field or method of the parent class. In child class if you have a field or method having the same name as in the parent class then the child class member overrides the parent class member of the same name. In that case if you want to access the member of the parent class then you can use super keyword.

Example code

In the example there is a display() method in class A and again display() method in the child class B which overrides the method of the parent class. In order to display the fields of class A if you want to invoke the display method of class A, you can do it using the super keyword.

Output

That’s all for the topic Super keyword in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.