[英]Chained calls to an object and inheritance in Java
在为链式调用声明方法时,通常会在方法结束时returns this
方法。
所以我宣布:
public class Foo {
public Foo setTitle(String title){
...
return this;
}
}
和:
public class Bar extends Foo{
/* OTHER STUFF */
}
如果你调用new Bar().setTitle("Test")
它会返回一个Foo
的引用。
为了清晰,简洁和可维护性,是否可以声明方法以自动返回Bar
的引用而不覆盖Bar中的方法 ?
谢谢
为了清晰,简洁和可维护性,是否可以声明方法以自动返回Bar的引用而不覆盖Bar中的方法?
不。你可以勾选一些奇怪的仿制品Foo<T extends Foo>
等 - 但它不会很令人满意。
基本上需要为“this type”提供一些语言支持,其中该类型的唯一有效表达式为null
和this
。 那不存在,所以你留下了压倒一切:
public Bar setTitle(String title) {
super.setTitle(title);
return this;
}
要么:
public Bar setTitle(String title) {
return (Bar) super.setTitle(title);
}
这只是继承最终成为痛苦的案例之一:(
我确实尝试过仿制药......
public class Foo<T extends Foo> {
public T setTitle(String title){
.....
return (T) this;
}
}
public class Bar extends Foo<Bar>{
/* OTHER STUFF */
}
似乎工作。
我认为它的actullay返回Bar
Only。 只需进行类型转换即可将对象引用为Bar
,如下所示:
Bar bar = (Bar)(new Bar().setTitle("Foo Title"));
System.out.println(bar.getTitle());//prints Foo Title
假设Foo
存在getTitle()
方法返回标题。
如果你在Bar
类中添加另一个方法,例如getBarTitle
:
public String getBarTitle(){
return getTitle()+" of Bar";
}
然后
System.out.println(bar.getBarTitle());//prints Foo Title of Bar
说明:当您在new Bar()
上调用setTitle
时,该方法在Bar
Object上调用, this
表示Bar
对象不是Foo
,因此它只返回Bar
onject,类类型为Foo
,这是超类。 在这个过程中,它不会改变原始的类类型,它根本就是条形,因此类型转换应该适合你的目的。
您可以使用具有上限的泛型:
public class Foo<T extends Foo<T>> {
public T setTitle() {
...
return (T) this;
}
}
public class Bar extends Foo<Bar> {
....
}
为了预防,它不返回Foo引用,它返回一个Bar引用,您可以使用System.out.println(reference.getClass()。getName())进行检查。
当你写作时,以同样的方式,
List l=new ArrayList();
(忘记LIst是一个界面,它是旁边的点)
l
实际上是对ArrayList的引用,即使这个信息是“隐藏”的,但调用l.someMathod()调用ArrayList方法,而不是List方法 - 这就是Object Orientation的工作原理!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.