Instance Methods & this
Home ] Up ] Instance Members ] [ Instance Methods & this ] Intializers & final Values ]

 

 

Let's show the Circle class again:

import java.lang.Math;

public class Circle
{
    // Accessor methods
    public double getX()      { return m_x; }
    public double getY()      { return m_y; }
    public double getRadius() { return m_r; }
    // Mutator methods
    public void setX(double v)      { m_x = v; }
    public void setY(double v)      { m_y = v; }
    public void setRadius(double r) { m_r = r; }
    // Operations/Attributes
    public double getCircumference()
                { return 2 * Math.PI * m_r; }
    public double getArea()
                { return Math.PI * m_r*m_r; }

    double m_x, m_y; // coordinates of center
    double m_r; // radius
}

The above methods are actually instance methods.

This means that each method 'knows' which instance it is being called against.

For example, if we have code like:

Circle c1 = new Circle();
Circle c2 = new Circle();
double r1 = c1.getRadius();
double r2 = c2.getRadius();

the calls to each getRadius() method will return the size of the radius for its respective instance.

The code for getRadius() looks like:

public class Circle
{
 // ...
 public double getRadius() { return m_r; }
 // ...
}

which could have been written:

public class Circle
{
 // ...
 public double getRadius() { return this.m_r; }
 // ...
}

Essentially, the call to the method:

double r1 = c1.getRadius();

appears as if it were being called like this:

double r1 = getRadius(c1);

and as if the method were defined:

public double getRadius(Circle this) { return this.m_r; }

In other words, it is as if there is a hidden parameter being implicitly passed to the function.

this:

  • is an implicitly declared variable
  • is local to each instance method
  • references the instance against which the method was invoked
  • is normally implicit;  however, there are times when you need to use this explicitly (see later).
 

This page was last modified on 02 October, 2007