Normally, I use this
in constructors only.
I understand that it is used to identify the parameter variable (by using this.something
), if i
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this
reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank
call for the audi
object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank
method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank
method in the Car
class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this
reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this
reserved word so you don't have to add it, it's a matter of preference. You can not use this
without a dot(.) because those are the rules of java ( the syntax).
In summary.
this
on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter. this
cannot be used without a dot(.) this is syntactically invalidthis
can also be used to distinguish between local variables and global variables that have the same namethis
reserve word also applies to methods, to indicate a method belongs to a particular object.