当为链式调用声明一个方法时,通常它会在方法结束时返回这个
。
所以我声明:
public class Foo {
public Foo setTitle(String title){
...
return this;
}
}
和:
public class Bar extends Foo{
/* OTHER STUFF */
}
如果您调用 new Bar().setTitle("Test")
,它会返回一个 Foo
的引用。
为了清晰、简洁和可维护性,是否可以声明方法以便自动返回 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 extends Foo>
或类似的 - 但它不会很令人满意。
基本上,“这种类型”需要某种语言支持,这种类型的唯一有效表达式是 null
和 this
.那不存在,所以你只能重写:
public Bar setTitle(String title) {
super.setTitle(title);
return this;
}
或者:
public Bar setTitle(String title) {
return (Bar) super.setTitle(title);
}
这只是继承最终成为一种痛苦的情况之一:(
关于java - Java 中对象的链式调用和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333127/