Let's have class A with a method useful for chaining:
class A {
A foo() {
// do stuff
return this;
}
}
You could now do a.foo().foo().foo() (think: builder pattern). Let class B extend it:
class B extends A {
}
B b;
Now invoking b.foo() returns actual type B, but declared A. Therefore I cannot write:
B other = b.foo();
I would have to write either:
B other = (B) b.foo();
Or override foo() in B:
class B extends A {
@Override
B foo() {
super.foo();
return this;
}
}
Is there a nice way to do this?
Did this by implementing an additional generic method as(type) to the superclass. This helps to have a nicer cast for fluent interfaces.
class A {
public A foo() {
return this;
}
@SuppressWarnings("unchecked")
public <T extends A> T as(Class<T> clazz) {
return (T) this;
}
}
class B extends A {}
So you can write a.foo().as(B.class).methodOfB(..). And you do not need to reimplement foo() in all subclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With