In Java, the super
keyword is used to refer to the parent class or superclass of a subclass. It can be used to call the constructor, methods, and variables of the parent class.
Here are some common uses of the super
keyword in Java:
- Call the superclass constructor:
Thesuper()
constructor is used to call the constructor of the parent class. It should be the first statement in the constructor of the subclass, and it can be used with or without arguments. For example:
public class Parent {
public Parent(int x) {
// constructor code here
}
}
public class Child extends Parent {
public Child(int x, int y) {
super(x); // calls the Parent constructor with argument x
// constructor code here
}
}
- Call the superclass method:
Thesuper
keyword can also be used to call the method of the parent class with the same name. This is useful when the subclass wants to override the method but still wants to use the parent class’s implementation. For example:
public class Parent {
public void method() {
// method code here
}
}
public class Child extends Parent {
public void method() {
super.method(); // calls the Parent method
// additional code here
}
}
- Access the parent class variable:
Thesuper
keyword can also be used to access the variable of the parent class with the same name. This is useful when the subclass wants to use the parent class’s variable but also wants to add its own value to it. For example:
public class Parent {
public int x = 10;
}
public class Child extends Parent {
public int x = 20;
public void method() {
System.out.println(super.x + this.x); // prints 30
}
}
In this example, the super.x
refers to the x
variable of the parent class, while this.x
refers to the x
variable of the child class.