this Keyword

You use the this keyword from any method or constructor to refer to the current object. For example, if you have a class-level field with the same name as a local variable, you can use this syntax to refer to the former:

this.field

A common use is in the constructor that accepts values used to initialize fields. Consider the Box class in Listing 4.7.

Listing 4.7: The Box class

package app04;
public class Box {
    int length;
    int width;
    int height;
    public Box(int length, int width, int height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }
}

The Box class has three fields, length, width, and height. Its constructor accepts three arguments used to initialize the fields. It is very convenient to use length, width, and height as the parameter names because they reflect what they are. Inside the constructor, length refers to the length argument, not the length field. this.length refers to the class-level length field.

It is of course possible to change the argument names, such as this.

public Box (int lengthArg, int widthArg, int heightArg) {
    length = lengthArg;
    width = widthArg;
    height = heightArg;
}

This way, the class-level fields are not shadowed by local variables and you do not need to use the this keyword to refer to the class-level fields.

However, using the this keyword spares you from having to think of different names for your method or constructor arguments.