What does the super keyword do, and how does it differ from this?
The super keyword refers to the parent of the current object. It is the parent version of the this keyword, and it is how a child reaches the parts of the parent that it cannot get at on its own.
public class Main {
public static void main(String[] args) {
Employee e = new Employee("Ada", "Engineering", 50000);
System.out.println(e.describe());
}
}
And here is the parent and the child.
public class Person {
protected final String name;
public Person(String name) {
this.name = name;
}
public String describe() {
return "name: " + name;
}
}
public class Employee extends Person {
private final String department;
private final double salary;
public Employee(String name, String department, double salary) {
super(name);
this.department = department;
this.salary = salary;
}
@Override
public String describe() {
return super.describe() + ", department: " + department;
}
}
So what does it do? There are three things that you use it for.
what you write what it does
--------------------------- --------------------------------------------
super(args) runs the parent constructor
super.method() calls the parent version of the method
super.field reads the parent version of the field
And how does it differ from this? The difference is direction. The this keyword points at the current object and the super keyword points at the parent of the current object. So this.field is the current object's copy and super.field is the parent's copy.
the keyword the object it points at
-------------- ----------------------------------------
this the current object
super the parent of the current object
And there is one very important detail about the field case, and it catches everybody out. A field that is hidden, which means the child declares a field with the same name as the parent's, gives you two separate fields. So this.name is the child's field and super.name is the parent's field, and they can hold different values.
public class Parent {
protected String name = "parent";
}
public class Child extends Parent {
protected String name = "child";
public void printBoth() {
System.out.println(this.name); // child
System.out.println(super.name); // parent
}
}
And that is why hiding a field is a bad idea. The two names mean different things and the code is confusing, so you should rename one of them rather than hide it.
So the rule to remember is this. The super keyword is the parent of the current object, and the two fields with the same name are two different fields.
The last question in this topic is about when you need it and what goes wrong.