I have read that in Java you don\'t have to explicitly bind the this keyword to object, it is done by interpreter. It is opposite to Javascript where you
this
refers to current object.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
From the official documentation (found here):
Within an instance method or a constructor,
this
is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
What this means is that inside the code of any class, when you write this
, you specify the fact that you are referring to the current object.
As a side note, you cannot use this
with static fields or methods because they do not belong to any specific object (instance of the class).
The Java language specification states:
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
I.e. it always points to an object, not a class.
in java this is refer Current object
like
public class Employee{
String name,adress;
Employee(){
this.name="employee";
this.address="address";
}
}
In Java, this
always refers to an object and never to a class.
this keyword is always used in referencing the object of the current class. where as this() is used for the current class constructors. for example:
class circle {
public int radius;
public Circle() {
this.radius = 10; //any default value
}
public Circle(int radius) {
this.radius = radius // here this.radius will set instance variable radius
}
public int areaOfCircle() {
return 3.14*radius*radius;
}
}