3.9 - The this Keyword
Inside an instance method or constructor,
this is a special variable that refers to the current object, meaning whichever specific object’s method or constructor is actually running.public class Dog { private String name; public Dog(String name) { this.name = name; // this.name is the instance variable, name is the parameter } }
The keyword
this holds the same reference as the variable the method was called on. In rex.isSameDog(alias), this refers to the same object rex does:public boolean isSameDog(Dog other) { return this == other; // true only if other refers to the current object } Dog rex = new Dog("Rex"); Dog alias = rex; Dog twin = new Dog("Rex"); System.out.println(rex.isSameDog(alias)); // true, same object System.out.println(rex.isSameDog(twin)); // false, a different object with the same name
When nothing is shadowed,
this.name and plain name mean the same thing, so this is optional there.This is exactly how you fix the shadowing problem from 3.8,
this.name clearly means the instance variable, while plain name means the parameter.You can also pass
this as an argument to another method, if you need to hand off a reference to the current object.public class Dog { public void register(DogShelter shelter) { shelter.addDog(this); // passing the current object itself } }
Here’s a full example in one class. The
isYoungerThan method passes the current dog as an argument to the other dog’s isOlderThan method:public class Dog { private String name; private int age; public Dog(String name, int age) { this.name = name; this.age = age; } public boolean isOlderThan(Dog other) { return age > other.age; } public boolean isYoungerThan(Dog other) { return other.isOlderThan(this); // asks the other dog: are you older than me? } } Dog rex = new Dog("Rex", 3); Dog max = new Dog("Max", 5); System.out.println(rex.isYoungerThan(max)); // true System.out.println(max.isYoungerThan(rex)); // false
One thing to remember: class methods (
static ones) don’t have access to this at all, since this only makes sense in the context of a specific object, and static methods aren’t tied to any particular object.public static void resetName() { this.name = "Unknown"; // compile error: a class method has no this }