When declaring a method for chained calls usually it returns this at the end of the method.
So I declare:
public class Foo {
public Foo setTitle(String title){
...
return this;
}
}
And:
public class Bar extends Foo{
/* OTHER STUFF */
}
If you call new Bar().setTitle("Test") it returns a Foo‘s reference.
Is possible to declare the method in order to return automatically a Bar‘s reference without override the method in Bar for clarity, brevity and maintainability?
Thanks
No. You could hook up some weird generics –
Foo<T extends Foo>or the like – but it wouldn’t be very satisfactory.Basically there’s need to be some language support for “this type”, where the only valid expressions of that type were
nullandthis. That doesn’t exist, so you’re left with overriding:Or:
It’s just one of those cases where inheritance ends up being a pain 🙁