How does the super keyword work in Java, and what is the difference between super(), super.field and super.method()?
The keyword super means "the parent of this object", and it comes in three forms. They look the same and they do completely different jobs.
super(...) is a call to a constructor of the parent class. It has to be the first statement of your constructor, and it is how you make sure the parent part of the object is set up.
super.field reaches a field of the parent when your own class declares a field with the same name. The plain name would give you your own field, and the word super tells the compiler that you want the parent's one.
super.method() calls the parent's version of a method that you have overridden. It is how you add to the parent's behaviour rather than replacing it.
public class Main {
public static void main(String[] args) {
Child child = new Child("Ada");
System.out.println("name : " + child.getName());
// The parent's field and the child's field have the same name.
System.out.println("child : " + child.getLabel());
System.out.println("parent: " + child.getParentLabel());
}
}
class Parent {
protected String label = "parent label";
Parent(String name) {
this.label = name;
}
String greet() {
return "hello from the parent";
}
}
class Child extends Parent {
private String label = "child label";
Child(String name) {
// The parent constructor has to be called first.
super(name);
}
@Override
String greet() {
// Use the parent's version and add to it.
return super.greet() + ", and from the child";
}
String getLabel() {
return this.label;
}
String getParentLabel() {
return super.label;
}
}
The next question in this topic looks at the rule about where the super call has to go.