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

  1. Referring to Current Object

  2. Accessing Instance Variables (when shadowed by local variables)

  3. Calling Another Constructor (constructor chaining)

  4. Passing Current Object as a Parameter

  5. Calling Current Class Methods


2. Example 1: Accessing Instance Variables


 

📌 Output:

Name: Alice

Without this, name = name; would refer to the local parameter, not the instance variable.


3. Example 2: Calling Another Constructor (Constructor Chaining)


 

📌 Output:

Brand: Unknown, Year: 0
Brand: Toyota, Year: 2022

4. Example 3: Passing Current Object as Parameter


 

📌 Output:

Hello, Alice

5. Example 4: Calling Current Class Method


 

📌 Output:

Sum = 15

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.

You may also like...