链接在Java中调用对象和继承 [英] Chained calls to an object and inheritance in Java
问题描述
当声明链式调用的方法时,会在方法结束时返回此
。
When declaring a method for chained calls usually it returns this
at the end of the method.
所以我声明:
public class Foo {
public Foo setTitle(String title){
...
return this;
}
}
并且:
public class Bar extends Foo{
/* OTHER STUFF */
}
如果你打电话给新的Bar()。setTitle(Test)
它返回 Foo
的引用。
If you call new Bar().setTitle("Test")
it returns a Foo
's reference.
可以声明方法以便自动返回 Bar
的参考为了清晰,简洁和可维护性而没有覆盖Bar 中的方法?
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?
谢谢
推荐答案
可以声明方法,以便自动返回Bar的引用而不覆盖Bar中的方法是为了清晰,简洁和可维护性?
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?
否。你可以联系一些奇怪的泛型 - Foo< T延伸Foo>
等等 - 但这不会很令人满意。
No. You could hook up some weird generics - Foo<T extends Foo>
or the like - but it wouldn't be very satisfactory.
基本上需要为this type提供一些语言支持,其中该类型的唯一有效表达式是 null
和这个
。这不存在,所以你留下了重写:
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;
}
或者:
public Bar setTitle(String title) {
return (Bar) super.setTitle(title);
}
这只是继承最终成为痛苦的案例之一:(
It's just one of those cases where inheritance ends up being a pain :(
这篇关于链接在Java中调用对象和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!