The Keyword this
The this keyword refers to the current object.
When you create an object, Java keeps track of which object is calling an instance method or constructor. Inside that method or constructor, this refers to that object.
The this keyword is especially useful when a parameter has the same name as an instance variable.
Using this with Instance Variables
Consider a Dice class with a sides instance variable.
There are two variables named sides in the constructor:
this.sidesis the instance variable belonging to theDiceobject.-
sidesis the parameter passed to the constructor.
The statement
assigns the value of the parameter to the object's instance variable.
Without this, Java would treat both references to sides as the parameter.
Why Use this?
Using the same names for parameters and instance variables is a common Java style.
For example:
The constructor parameter describes the value being provided, while this.model identifies the field stored in the current Car object.
this Refers to the Current Object
Suppose you create two Dice objects.
When the constructor runs for dice1, this refers to dice1.
When the constructor runs for dice2, this refers to dice2.
Each object therefore gets its own value for sides.
Calling Another Method with this
The this keyword can also be used to call another instance method on the current object.
This is equivalent to:
Using this makes it explicit that the method belongs to the current object.
A Common Pattern
One common use of this is in constructors:
The this keyword makes it clear which variables belong to the object and which values come from the constructor parameters.