This Keyword In Java With Program And Examples

Explain This Keyword In Java With Program And Examples, This keyword Program With Explanation, Why Use This Keyword In Java 

In This Topic & Blog Having Any Query Then Post your Comment and Suggestion Below

this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the
this
keyword.
this
can be used inside any method to refer to the  current  object. That is,
this
is always a reference to the object on which the method was invoked. You can use
this
anywhere a reference to an object of the current class’ type is permitted.
To better understand what
this
refers to, consider the following version of
Box( )
:
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
This version of
Box( )
operates exactly like the earlier version. The use of
this
is redundant,
but perfectly correct. Inside
Box( ) this
,
will always refer to the invoking object. While it is
redundant in this case,
this
is useful in other contexts, one of which is explained in the next
section.
120
Part I:
The Java Language


        
Chapter 6:
Introducing Classes
121
Instance Variable Hiding
As you know, it is illegal in Java to declare two local variables with the same name inside
the same or enclosing scopes. Interestingly, you can have local variables, including formal
parameters to methods, which overlap with the names of the class’ instance variables. However,
when a local variable has the same name as an instance variable, the local variable  hides  the
instance variable. This is why
width height
,
, and
depth
were not used as the names of the
parameters to the
Box( )
constructor inside the
Box
class. If they had been, then
width
would
have referred to the formal parameter, hiding the instance variable
width
.
While it is usually
easier to simply use different names, there is another way around this situation. Because
this
lets you refer directly to the object, you can use it to resolve any name space collisions that
might occur between instance variables and local variables. For example, here is another
version of
Box( )
, which uses
width height
,
, and
depth
for parameter names and then uses
this
to access the instance variables by the same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
A word of caution: The use of
this
in such a context can sometimes be confusing, and
some programmers are careful not to use local variables and formal parameter names that
hide instance variables. Of course, other programmers believe the contrary—that it is a good
convention to use the same names for clarity, and use
this
to overcome the instance variable
hiding. It is a matter of taste which approach you adopt.

Labels: