I have a parent class, which defines a collection of chainer methods (methods that return \"this\"). I want to define multiple child classes that contain their own chainer
Here's an improvement on OldCurmudgeon's method:
public class Parent> {
@SuppressWarnings("unchecked")
private final This THIS = (This)this;
public This foo() {
//...
return THIS;
}
public This bar() {
//...
return THIS;
}
}
public class Child extends Parent {
// you can override super with covariant return type
@Override
public Child bar() {
super.bar();
return this;
}
}
Child child =
new Child()
.foo()
.bar();
The improvement is making an unchecked cast only once and save it to a constant THIS, which you can reuse as the return value for method chaining.
This removes unchecked casts in every method and makes the code clearer.
You can override Parent's methods by returning Child instead of This (covariant return type).