What is the difference between this and super in Java?
this refers to the current object, and this(...) calls another constructor of the same class. super refers to the parent class part of the object, and super(...) calls a parent constructor.
Explain it simply
Inside a family, "this" is you, speaking about yourself. "super" is you pointing at your parent: "my father's way of doing it".
Example
class Person {
String name = "person";
void intro() { System.out.println("I am a person"); }
}
class Student extends Person {
String name = "student";
void show(String name) {
System.out.println(name); // prints the parameter
System.out.println(this.name); // prints: student
System.out.println(super.name); // prints: person
}
@Override
void intro() {
super.intro(); // prints: I am a person
System.out.println("and a student");
}
}
new Student().show("local"); // prints: local, student, personWhat to say in the interview
"this is the reference to the current object. I use it to separate a field from a parameter with the same name, to pass the current object around, or to chain constructors with this(...). super gives access to the parent's fields and methods hidden or overridden by the child, and super(...) calls a parent constructor. Both this(...) and super(...) must be the first statement of a constructor, so only one of them can appear. Neither can be used in a static context."
Common mistakes
- Writing both this(...) and super(...) in the same constructor.