What does the this keyword refer to in Java, and where is it actually useful?
The keyword this means "the object that this code is running on". It is a reference to the current object, and it is available inside every instance method and inside every constructor.
There are three places where it is genuinely useful.
The first one is when a parameter has the same name as a field. The name then belongs to the parameter, and you use this.field to reach the field.
The second one is when you want to hand the current object to another method. A method such as register often needs to know who is registering, and passing this is the way to say it.
The third one is when you want one method of the object to call another method of the same object, and you want to be clear that you mean the method of this object.
public class Main {
public static void main(String[] args) {
Account account = new Account("Ada", 100);
account.printDetails();
account.describeTo(new Printer());
}
}
class Account {
private final String owner;
private int balance;
Account(String owner, int balance) {
this.owner = owner;
this.balance = balance;
}
void printDetails() {
// this makes it clear that these are the fields of this object.
System.out.println("owner : " + this.owner);
System.out.println("balance : " + this.balance);
}
void describeTo(Printer printer) {
// this is passed to another method so that it knows who is talking.
printer.print(this);
}
}
class Printer {
void print(Account account) {
System.out.println("printed an account that belongs to " + account.getOwner());
}
}
One thing that this cannot do is appear in a static method. A static method belongs to the class and has no object behind it, so there is no this to write. The compiler tells you so if you try.
The next question in this topic looks at the shadowing problem that this solves most often.