Java Reference
In-Depth Information
// Instance method to calculate volume
double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
// Plus the rest of the class definition...
}
You can see that the volume() method is an instance method because it is not declared as static. It has
no parameters, but it does return a value of type double — the calculated volume. The method uses the
class variable PI and the instance variable radius in the volume calculation — this is the expression 4.0/
3.0*PI*radius*radius*radius (corresponding to the formula (4/3)πr 3 for the volume of a sphere) in the
return statement. The value that results from this expression is returned to the point where the method is
called for a Sphere object.
You know that each object of the class has its own separate set of instance variables, so how is an instance
variable for a particular object selected in a method? How does the volume() method pick up the value of a
radius variable for a particular Sphere object?
The Variable this
Every instance method has a variable with the name this that 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
inserts the this object reference so that the reference is equivalent to this.radius . The return statement in
the definition of the volume() method is actually the following:
return 4.0/3.0*PI*this.radius*this.radius*this.radius;
The statement actually refers to the radius field for the object referenced by the variable this . In gener-
al, 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 you will 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() refers to the object
ball , so the instance variable radius for the ball object is used in the calculation.
NOTE I 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
Search WWH ::




Custom Search