super() in Java
In Java, the super
keyword is used to refer to the superclass of the current class. It is often used to call the constructor of the superclass, or to access methods or fields of the superclass that have been overridden in the current class.
Here are some examples of how the super
keyword is commonly used in Java:
- Calling the superclass constructor:
public class Subclass extends Superclass {
public Subclass() {
super(); // calls the constructor of the Superclass
}
}
- Accessing overridden methods:
public class Superclass {
public void method() {
System.out.println("In Superclass");
}
}
public class Subclass extends Superclass {
@Override
public void method() {
super.method(); // calls the method() in Superclass
System.out.println("In Subclass");
}
}
- Accessing overridden fields:
public class Superclass {
protected int field = 1;
}
public class Subclass extends Superclass {
private int field = 2;
public void printField() {
System.out.println(super.field); // prints 1
System.out.println(this.field); // prints 2
}
}
I hope this helps! Let me know if you have any questions.