The <code>this</code> Keyword in Java
this is an implicit final reference to the current instance. Inside a non-static method or constructor, this always points to the object the method was called on. Inside a static method, this isn't defined β no instance, no reference.
Disambiguating fields and parameters
public class User {
private String name;
public User(String name) {
this.name = name; // without `this.`, name = name just sets the parameter
}
public void setName(String name) {
this.name = name;
}
}
Constructor chaining with this(...)
public class Rectangle {
private final int w, h;
public Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
public Rectangle(int side) {
this(side, side); // call another constructor
}
public Rectangle() {
this(1); // delegate all the way down
}
}
this(...) must be the first statement of the constructor.
Fluent builders β return this
public class QueryBuilder {
private String table;
private String where;
public QueryBuilder from(String table) { this.table = table; return this; }
public QueryBuilder where(String w) { this.where = w; return this; }
public String build() { return "SELECT * FROM " + table + " WHERE " + where; }
}
String q = new QueryBuilder()
.from("users")
.where("age > 18")
.build();
this in a nested class
public class Outer {
private final String name;
public Outer(String name) { this.name = name; }
public class Inner {
public String describe() {
return Outer.this.name; // qualified this β reach the outer instance
}
}
}
Common mistakes
- Using
thiseverywhere β only needed to disambiguate or in constructor/builder chains. - Leaking
thisfrom a constructor β registering the half-constructed object somewhere (an observer, a static list). Other threads could see a partially initialised object. - Calling overridable methods from a constructor β technically
this.someMethod(), but the subclass override runs before the subclass is fully constructed.
Related
Pillar: Java keywords. See also super, constructors.