The this and super keywords are special reference variables in Java used to access members of the current class and parent class, respectively. The this keyword refers to the current object, while the super keyword refers to the immediate parent class object.
Key Points: • this is used to refer to the current class instance. • super is used to access members of the immediate parent class. • this can be used to access instance variables, methods, and constructors of the current class. • super can be used to access overridden methods, parent class variables, and parent constructors. • Both keywords help resolve naming conflicts between parent and child classes.
Example: Suppose both a parent class and a child class have a variable named name. The this keyword refers to the child class variable, while super refers to the parent class variable.
Code Example:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println(this.name);
System.out.println(super.name);
}
}
public class Demo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.display();
}
}Output:
Dog
AnimalCommon Uses of this:
• Refer to current class instance variables
this.name = name;
• Call current class methods
this.display();
• Invoke another constructor in the same class
this("Java");
Common Uses of super:
• Access parent class variables
super.name;
• Call parent class methods
super.display();
• Invoke parent class constructor
super();
Example of Constructor Usage:
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super();
System.out.println("Child Constructor");
}
}Output:
Parent Constructor Child Constructor
Difference Between this and super:
this: • Refers to current class object • Accesses current class members • Calls current class constructor using this()
super: • Refers to parent class object • Accesses parent class members • Calls parent class constructor using super()
Interview Tip: A concise interview answer is:
"'this' refers to the current class object and is used to access its variables, methods, and constructors. 'super' refers to the immediate parent class object and is used to access parent class variables, methods, and constructors, especially when they are hidden or overridden in the child class."