this vs super
⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min
TL;DR
this: A reference to the current object (the instance whose method or constructor is being called).super: A reference to the parent class of the current object.
Concept
The this Keyword
- Resolves ambiguity between instance variables and local variables/parameters.
this()invokes another constructor within the same class (Constructor Chaining).- Used to pass the current object as a parameter to other methods.
The super Keyword
- Accesses hidden fields or overridden methods in the parent class.
super()invokes the constructor of the parent class.
Examples
class Parent {
String name = "ParentName";
public Parent(String message) {
System.out.println("Parent constructor: " + message);
}
}
class Child extends Parent {
String name;
public Child(String name) {
// 1. super() - Calling parent constructor
super("Hello from child");
// 2. this - Resolving naming ambiguity
this.name = name;
}
// Constructor Chaining using this()
public Child() {
this("Default Name");
}
public void printNames() {
System.out.println("Child name: " + this.name);
// 3. super - Accessing hidden parent field
System.out.println("Parent name: " + super.name);
}
}
Interview Questions
Q: Where must this() or super() be placed inside a constructor?
A: They must be the very first statement in the constructor. Therefore, you cannot use both this() and super() inside the exact same constructor.
Q: Can you use this or super inside a static method?
A: No. Static methods belong to the class, not to an instance. this refers to “this current object,” and super refers to “this current object’s parent.” Since there is no object context in a static method, using either keyword results in a compile-time error.