this refers to the current object. super refers to the parent class part of the current object.
this
Use this to access current object members.
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Without this.name, the parameter can shadow the field.
Uses of this
- Access current object's variables.
- Call another method of the same object.
- Call another constructor using
this().
Student() {
this("Unknown");
}
super
Use super to access parent members or call the parent constructor.
class WebhookEvent extends DomainEvent {
WebhookEvent() {
super();
}
void publish() {
super.publish();
System.out.println("Webhook delivered");
}
}
this vs super
| this | super |
|---|---|
| Current object | Parent class part |
| Current class fields/methods | Parent fields/methods |
this() calls same-class constructor |
super() calls parent constructor |
Interview Notes
this()andsuper()must be first statement in a constructor.- They cannot both be called in the same constructor.
- Static methods cannot use
thisorsuper. - Java inserts
super()automatically if no parent constructor call is written and the parent has a no-arg constructor.