The keyword "this" references the current object. What does that mean? Thank you.
Printable View
The keyword "this" references the current object. What does that mean? Thank you.
So when we write a java class, and instantiate that class as an object, the code executing inside said object and reference itself using the keyword this. It is a common idiom when working with constructors or setter methods, but can be used all over the place.
For example:
In this example, we have a constructor that takes a parameter called 'a' which coincidentally is also the name of the declared instance variable above it. When we say "this.a = a;" we're literally saying "the 'a' belonging to the Alpha instance we are currently in should be assigned the value contained in the parameter named 'a'".Code:public class Alpha{
int a;
public Alpha(int a){
this.a = a;
}
}
You'll also see it used quite a bit when working with actionListeners and GUIs - frequently one will implement an interface and then pass a reference to the current class (this) to a method that assigns an action listener.