this Keyword
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 likep1.spam()
,this
refers to thep1
object- if we made another object of the same type
p2
and calledp2.spam()
,this
would 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
this
or 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!
this
can distinguish between parameter variables and instance variablesthis
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!
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.