OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 10 : this Keyword in Java
Unit - 2
Topic - 10 : this
Keyword in Java
In Java, sometimes a method needs to refer to the object that invoked it.
To enable this, Java provides the this
keyword.
What is this
?
-
this
is a reference to the current object (the object whose method or constructor is being executed). -
You can use
this
anywhere a reference to the current object is needed. -
It’s implicitly passed to instance methods and constructors.
1. Simple Use of this
in a Constructor
Even if you don't explicitly use this
, Java automatically applies it when accessing instance variables.
Example:
Output:
💡 Explanation:
Here, this.width
refers to the instance variable, and w
is the constructor parameter. Without this
, the assignment would be ambiguous when parameter names match instance variable names.
2. Instance Variable Hiding
When local variables or method parameters have the same name as instance variables, they hide the instance variables.
In such cases, this
is used to refer to the instance variable.
Output:
💡 Explanation:
Without this
, name = name;
would assign the parameter to itself, leaving the instance variable uninitialized.
3. Other Uses of this
-
Calling another constructor in the same class:
this(arguments)
-
Passing the current object as a parameter to another method:
someMethod(this);
-
Returning the current object from a method for method chaining.
Key Points
-
this
always refers to the current object. -
Avoid variable name conflicts when possible, but use
this
when necessary. -
Helpful for constructor chaining, method chaining, and passing current object.
Comments
Post a Comment