Java Reference
In-Depth Information
We know that each object of the class will have its own separate set of instance variables, so how is an
instance variable for a particular object selected in a method? How does our
volume()
method pick up
the radius for a particular
Sphere
object?
The Variable this
Every instance method has a variable with the name,
this
, which refers to the current object for which
the method is being called. The compiler uses this implicitly when your method refers to an instance
variable of the class. For example, when the method
volume()
refers to the instance variable
radius
,
the compiler will insert the
this
object reference, so that the reference will be equivalent to
this.radius
. The return statement in the definition of the
volume()
method is actually:
return 4.0/3.0*PI*this.radius*this.radius*this.radius;
In general, every reference to an instance variable is in reality prefixed with
this.
You could put it in
yourself, but there's no need, the compiler does it for you. In fact, it is not good practice to clutter up your
code with
this
unnecessarily. However, there are occasions where you have to include it, as we shall see.
When you execute a statement such as:
double ballVolume = ball.volume();
where
ball
is an object of the class
Sphere
, the variable
this
in the method
volume()
will refer to the
object
ball
, so the instance variable
radius
for this particular object will be used in the calculation.
We mentioned earlier that only one copy of each instance method for a class exists in
memory, even though there may be many different objects. You can see that the
variable
this
allows the same instance method to work for different class objects.
Each time an instance method is called, the
this
variable is set to reference the
particular class object to which it is being applied. The code in the method will then
relate to the specific data members of the object referred to by
this
.
We have seen that there are four different potential sources of data available to you when you write the
code for a method:
Arguments passed to the method, which you refer to by using the parameter names.
Data members, both instance variables and class variables, which you refer to by their
variable names.
Local variables declared in the body of the method.
Values that are returned by other methods that are called from within the method.
The names of variables that are declared within a method are local to the method. You can use a name
for a local variable or a parameter in a method that is the same as that of a class data member. If you
find it necessary to do this then you must use the name
this
when you refer to the data member of the
class from within the method. The variable name by itself will always refer to the variable that is local to
the method, not the instance variable.