The uses below are in addition to those demonstrated at this keyword.

Using this to call an instance method on the implicit parameter

The Coordinate2D method getDistance calculates the distance betweeen the implicit parameter (the object on which it is run) and the explicit parameter (the object passed as otherCoor).

public double getDistance(Coordinate2D otherCoor)
{
    int xSqrd = this.getX() - otherCoor.getX();
    xSqrd *= xSqrd;

    int ySqrd = this.getY() - otherCoor.getY();
    ySqrd *= ySqrd;

    return Math.sqrt(xSqrd + ySqrd);
}

this.getX() calls the getX method on the implicit parameter. otherCoor.getX() calls the getX method on the explicit parameter otherCoor.

Prefacing calls to methods on the implicit parameter with this. is optional. Calls to instance methods are assumed to be on the implicit parameter unless otherwise specified. The getDistance method would work the same if both occurrences of this. were removed.

On AP CS A Exam Free Response, consider omitting this. when calling methods on the implicit parameter. Including this. doesn’t change the behavior. If this. is accidentally used to call a static method (which would be incorrect), it could result in a penalty.

Using this to call one constructor from another

The Coordinate2D constructor without parameters explicitly sets the instance variables x and y to 0.

The constructor could be written as:

public Coordinate2D()
{
   this(0, 0);
}

The this keyword can be used to call a constructor from another constructor. The call must be the first line in the constructor.

Using this to refer to the implicit parameter

The Coordinate2D equals method contains the code segment below.

if(this == other)
    return true;

The condition checks if the explicit parameter other stores a reference to the implicit parameter this.

Consider the main method below.

public static void main(String[] args)
{
    Coordinate2D c1 = new Coordinate2D(1, 2);
    Coordinate2D c2 = new Coordinate2D(1, 2);
    Coordinate2D c3 = c1;
    
    System.out.println(c1.equals(c1));  // Line 1
    System.out.println(c1.equals(c2));  // Line 2
    System.out.println(c1.equals(c3));  // Line 3
}

All 3 lines print true, but based on different code in the equals method.

Line 1 and Line 3 print true because the implicit and explicit parameters are the exact same object. this == other evaluates to true.

Line 2 prints true because of code later in the equals method. c1 and c2 refer to (store the memory addresses of) different objects. this == other evaluates to false.

Comments

Comment on this keyword