Qualified this
Java's
this keyword is quite a handy little feature. It lets you get a reference to the current
instance of a particular object which is useful in a variety of cases.
Probably the most common use case of the
this keyword is to disambiguate variable references in
constructors:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
}
Without the
this keyword Java would not be able to tell which
name
variable we are assigning.
A more complex example involves passing
this as a parameter to a method.
class Builder {
private String name;
public Builder(String name) {
this.name = name;
}
public Creation build() {
return new Creation(this);
}
}
class Creation {
private Builder builder;
public Creation(Builder builder) {
this.builder = builder;
}
}
Notice how in line 9
this is being passed to the
Creation constructor.
Because we are inside of the
Builder class (referred to as the Outer Class)
this is an instance
of the
Builder class. Thus,
this is a valid paramter to pass to the
Creation constructor because its type is
Builder.
Now let's look at some even more complex code:
interface Builder {
public Creation build();
}
class MasterBuilder {
private final String name;
public MasterBuilder(String name) {
this.name = name;
}
private Builder builder = new Builder() {
@Override
public Creation build() {
return new Creation(MasterBuilder.this);
}
};
public Builder getBuilder() {
return builder;
}
}
class Creation {
private MasterBuilder builder;
public Creation(MasterBuilder builder) {
this.builder = builder;
}
}
The
Builder instance created on line 12 is an Inner Class because it is defined inside of
another class (the Outer Class). When we call the
Creation constructor in line 15 we need to
use
this to get a reference to the current instance of
MasterBuilder
but inside of the Inner Class
this is an instance of
Builder which is
the wrong type. To fix this we use a Qualified
this to specify that we want the current instance
of the Outer Class. This is as simple as using:
[OuterClassName].
this in
your code.