this is used to refer to the current object instance.
super is used to refer to the variables and methods of the superclass of the current object instance.
In Java, this
and super
are keywords used to refer to the current object and the parent class respectively. Here’s how they are used:
this
keyword:- It refers to the current instance of the object.
- It is primarily used to differentiate instance variables from local variables when they have the same name.
- It can be used to invoke the current object’s method.
- It can be passed as an argument to other methods.
- It can be used to call the current class constructor.
Example:
java
public void setX(int x) {public class MyClass {
private int x;
// Using “this” to differentiate between instance variable and parameter
this.x = x;
}
public void display() {
// Using “this” to invoke the current object’s method
System.out.println(“Value of x: “ + this.x);
}
}super
keyword:- It is used to refer to the immediate parent class object.
- It is primarily used to invoke the parent class methods, access parent class fields, and call the parent class constructor.
- It is often used in cases where a subclass overrides a method defined in the superclass and wants to call the superclass version of the method.
Example:
java
class Dog extends Animal {class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
void eat() {
// Using “super” to invoke the parent class method
super.eat();
System.out.println(“Dog is eating”);
}
}
In summary, this
is used to refer to the current object, while super
is used to refer to the immediate parent class object. The usage of these keywords depends on the context and the specific requirements of your code.