• this can be used in a class to refer to the current calling object
    • if we have an object p1 and we call a method like p1.spam(), this refers to the p1 object
      • if we made another object of the same type p2 and called p2.spam(), this would refer to p2
public class Spam {
    private int snake;

    public Spam(int snake) {
        //           ๐Ÿ‘‡ refers to the local variable
        this.snake = snake;
        // ๐Ÿ‘† refers to the instance variable
    }
}
  • static methods cannot refer to this or instance variables
    • they are called with a class name, not an object!
      • thereโ€™s no object to refer to
  • this can distinguish between parameter variables and instance variables
  • this can be used anywhere you can use an object variable
    • you can pass it to another method as an argument!

Summary: 5.9.2

  • this is a reference to the current object within a non-static method or constructor (the object whose method/constructor is being called)
  • this.instanceVariable can distinguish between instance variables and local parameters if variables have the same names
  • static methods cannot use this
  • this can be used anywhere you would use an object variables
    • even in arguments!