Java this Keyword
🔹 Java this Keyword
The this keyword in Java is a reference variable that refers to the current object. It is mainly used to differentiate instance variables from local variables and to call constructors or methods of the current class.
✅ 1. Uses of this Keyword
-
Referring to Current Object
-
Accessing Instance Variables (when shadowed by local variables)
-
Calling Another Constructor (constructor chaining)
-
Passing Current Object as a Parameter
-
Calling Current Class Methods
✅ 2. Example 1: Accessing Instance Variables
📌 Output:
Without
this,name = name;would refer to the local parameter, not the instance variable.
✅ 3. Example 2: Calling Another Constructor (Constructor Chaining)
📌 Output:
✅ 4. Example 3: Passing Current Object as Parameter
📌 Output:
✅ 5. Example 4: Calling Current Class Method
📌 Output:
✅ 6. Key Points About this
| Usage | Purpose |
|---|---|
this.variable |
Refers to current object’s instance variable |
this() |
Calls another constructor in the same class |
this.method() |
Calls another method of the current object |
this as parameter |
Pass current object to another method or constructor |
-
Helps resolve ambiguity between local and instance variables.
-
Can be used for constructor chaining but must be the first statement in a constructor.
