Back to: Java Tutorials
The super
keyword is used to access and invoke the methods, constructors, and properties of a parent class from a subclass. It is commonly used in inheritance when a subclass needs to access or override the methods or properties of its parent class.
Syntax:
super.methodName(); // calls parent class method
super.variableName; // accesses parent class variable
super(); // calls parent class constructor
When a subclass is created, it automatically inherits all the methods and properties of its parent class. However, if the subclass needs to modify or add to the functionality of the inherited methods or properties, it can use the super
keyword to access and modify the parent class members.
Example:
/**
* Java super keyword example parent class
*
* @author Mamun Kayum
*
*/
public class Parent {
int x = 10;
public void display() {
System.out.println("Parent class method");
}
}
/**
* Java super keyword example child class
*
* @author Mamun Kayum
*
*/
class Child extends Parent {
int y = 20;
public void display() {
super.display(); // calling parent class method
System.out.println("Child class method");
}
public void show() {
System.out.println("Parent class variable: " + super.x); // accessing parent class variable
System.out.println("Child class variable: " + y);
}
}
/**
* Java super keyword example caller class
*
* @author Mamun Kayum
*
*/
public class CallerMain {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
obj.show();
}
}
Output:
Parent class method
Child class method
Parent class variable: 10
Child class variable: 20
In the above example, the Child
class extends the Parent
class and overrides its display()
method. The super
keyword is used to call the parent class display()
method and then the Child
class display()
method is executed.
Similarly, the super
keyword is used to access the x
variable of the parent class from the show()
method of the Child
class.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author