Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


The Method Body

The method body is where all of the action of a method takes place; the method body contains all of the legal Java instructions that implement the method. Within the method body, you can use this to refer to the current object. The current object is the object whose method is being called. In addition, you can declare more variables within the method for exclusive use within that method.

this

Typically, within an object's method body you can just refer directly to the object's member variables. However, sometimes you need to disambiguate the member variable name if one of the arguments to the method has the same name.

For example, the following constructor for the HSBColor class initializes some of an object's member variables according to the arguments passed into the constructor. Each argument to the constructor has the same name as the object's member variable whose initial value the argument contains.

class HSBColor {
    int hue, saturation, brightness;
    HSBColor (int hue, int saturation, int brightness) {
        this.hue = hue;
        this.saturation = saturation;
        this.brightness = brightness;
    }
You must use this in this constructor because you have to disambiguate the argument hue from the member variable hue (and so on with the other arguments). Writing hue = hue; would make no sense. Argument names take precedence and hide member variables with the same name. So, to refer to the member variable you must do so through the current object--this--explicitly.

Some programmers prefer to always use this when referring to a member variable of the object whose method the reference appears. Doing so makes the intent of the code explicit and reduces errors based on name sharing.

You can also use this to call one of the current object's methods. Again this is only necessary if there is some ambiguity in the method name and is often used to make the intent of the code clearer.

super

You can also use super within the method body to refer to the current object's WHAT? [PENDING: more here.]

Local Variables

Within the body of the method you can declare more variables for use within that method. These variables are called local variables and live only while control remains within the method. This method declares a local variable i that it uses to iterate over the elements of its array argument.
Object findObjectInArray(Object o, Object arrayOfObjects[]) {
    int i;      // local variable
    for (i = 0; i < arrayOfObjects.length; i++) {
        if (arrayOfObjects[i] == o)
            return o;
    }
    return null;
}
After this method returns, i no longer exists.


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces