Please enable JavaScript to use CodeHS

Chapter 5

Writing Classes

5.9 this Keyword

As discussed in the previous section, when you use a variable in a method or constructor that shares the same name as an instance variable, by default, the local variable in the method or constructor is used. What if you want to refer to the instance variable?

this Keyword

It can often be confusing to know whether a variable in a constructor is referring to an instance variable or a variable that was passed in as an argument to the constructor. One way around this is to use different variable names for the instance variables and parameters, however using different names can get a little confusing.

Fortunately, Java has a way of specifying when you are referring to the object itself: this.

this refers to the current object. The this keyword allows you to be very clear whether you are referring to the object’s instance variable or a parameter:

public class BMX
{
  private String frameSize;
  private int numPegs;

  public BMX(String frameSize, int numPegs)
  {
    this.frameSize = frameSize;
    this.numPegs = numPegs;
  }
}
Plain text

Notice in the above example how you can use the same variable name. When the variable name is preceded by this., the variable is referring to the instance variable, otherwise it refers to the local variable.

Use this As An Actual Parameter

As noted above, the this keyword is used to represent the current object. With that in mind, you can use this to represent the current object as needed.

public class Rectangle {
  public int getArea(Rectangle rect) {
    return rect.getWidth() * rect.getHeight();
  }

  public boolean hasGreaterArea(Rectangle otherRect)
  {
    return getArea(this) > getArea(otherRect);
  }
}
Plain text

Notice in the example above how the getArea method is called using this as an actual parameter for input into the getArea method.

Rectangles and this

Student and this

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    Which of the following correctly uses the this keyword?

Exercise: Write Your Own CodeHS

We have constructed an Exercise Class for you.

The class should have a default constructor that takes no parameter and a constructor that takes three parameters. Complete the body of the constructor that takes three parameters but do not update the constructor heading.