There are certain coding techniques that require this
in Java, beyond cosmetic preference.
Here are two examples that I use fairly often.
First, if you want to use method chaining within a class so that the method returns the same type as the type it belongs to, you should use this.'
public class MyBuilder {
private long id;
private String name;
public MyBuilder id(long id) {
this.id = id;
return this;
}
public MyBuilder name(String name) {
this.name = name;
return this;
}
public AnotherType build() {
// business logic that consumes instance variables to build AnotherType
}
}
The other case is the Visitor pattern
public interface Visitor<V extends Visitable> {
public void visit(V visitable);
}
public interface Vistable<V extends Visitor> {
public void accept(V visitor);
}
And its implementations will say:
public class ConcreteVisitable implements Visitable<ConcreteVisitor> {
public void accept(ConcreteVisitor visitor) {
// grant access to ConcreteVisitable's state to the Visitor
visitor.visit(this);
}
}
public class ConcreteVisitor implements Visitor<ConcreteVisitable> {
public void visit(ConcreteVisitable target) {
// business logic that operates on the state of ConcreteVisitable
}
}
Notice that ConcreteVisitable
uses this
to allow its visitor's access to its state.
I'm using generics on the interfaces so that I can enforce a 1-1 mapping between ConcreteVisitor
s and ConcreteVisitable
s and so that ConcreteVisitor
s have particular knowledge of their targets without needing a class cast..