this Keyword
thiscan be used in a class to refer to the current calling object- if we have an object
p1and we call a method likep1.spam(),thisrefers to thep1object- if we made another object of the same type
p2and calledp2.spam(),thiswould refer top2
- if we made another object of the same type
- if we have an object
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
thisor instance variables- they are called with a class name, not an object!
- thereโs no object to refer to
- they are called with a class name, not an object!
thiscan distinguish between parameter variables and instance variablesthiscan be used anywhere you can use an object variable- you can pass it to another method as an argument!
Summary: 5.9.2
thisis a reference to the current object within a non-static method or constructor (the object whose method/constructor is being called)this.instanceVariablecan distinguish between instance variables and local parameters if variables have the same names- static methods cannot use
this thiscan be used anywhere you would use an object variables- even in arguments!

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.