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
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?
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 null and this. That doesn't exist, so you're left with overriding:
public Bar setTitle(String title) {
super.setTitle(title);
return this;
}
Or:
public Bar setTitle(String title) {
return (Bar) super.setTitle(title);
}
It's just one of those cases where inheritance ends up being a pain :(
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