Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Java Key Concepts

The this Key Word

 

 

When a method is called, it is automatically passed a reference to the invoking object. The reference this is a variable that is described below.
 
Every instance method (those not preceded with the keyword static - these are called class methods) has a variable with the name this, which refers to the current object for which the method is being called. This is used implicitly by the compiler when your method refers to an instance variable of the class.
 
class Sphere
{
    //class variables
    static final double PI = 3.14;           
    static int count = 0;                        //class variable to count objects
 
    //Instance variables
    double radius;                                //radius of a sphere
    double xCenter;                              //3D coordinate of the sphere
    double yCenter:
 
    //Instance method to calculate volume
    double volume ( )
    {
        return 4.0/3.0*PI*radius*radius*radius;
    }
    //plus the rest of the class definition...
    }
 
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. 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.

 

Note:
 
   Only one copy of each instance method for a class exists in memory, even though there may be many different objects. 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.

 

You can use a name for a local variable in a method, or possibly a parameter, that is the same as the name of a class data member. They will be hidden from each other. In this case, you must use the keyword this when you refer to the data member in the method.
 
For example, suppose you wanted to add a method to change the radius of a Sphere object to a new radius value which is passed as an argument. You could code this as:
 
void changeRadius (double radius)
{
    //change the instance variable to the argument value
    this.radius = radius;
}
 
In the body of the changeRadius ( ) method; the this.radius refers to the instance variable, and radius by itself refers to the parameter. There is no confusion in the duplication of names here. We are receiving a radius value as a parameter and storing it in the radius variable for the class object.