What does ‘super’ mean in Java?
In Java, the keyword “super” is used to refer to the parent class. It can access the parent class’s variables, methods, and constructors.
Specifically, it can be used in the following ways:
- To access members of the parent class: When a subclass and parent class have members with the same name, we can use the super keyword to distinguish which class’s member variable we want to access. For example, super.x means accessing the x member variable of the parent class.
- In a subclass, you can use the super keyword to call a method from the parent class, even if the subclass has a method with the same name. For example, super.method() calls the method from the parent class.
- Calling a parent class’s constructor: In the constructor of a child class, the super keyword can be used to call the parent class’s constructor in order to complete the initialization work of the parent class. For example, super() represents calling the parent class’s parameterless constructor, and super(x) represents calling the parent class’s constructor with parameter x.
Note: The “super” keyword can only be used in child classes and can only be used to directly access the members of the parent class.