2

当为链式调用声明方法时,通常returns this在方法的末尾。

所以我声明:

public class Foo {

    public Foo setTitle(String title){
        ...
        return this;
    }

}

和:

public class Bar extends Foo{

      /* OTHER STUFF */
}

如果你调用new Bar().setTitle("Test")它返回一个Foo' 的引用。

为了清晰、简洁和可维护性,是否可以声明该方法以自动返回 aBar的引用而不重写 Bar 中的方法?

谢谢

4

5 回答 5

6

是否可以声明该方法以自动返回 Bar 的引用,而无需为了清晰、简洁和可维护性而重写 Bar 中的方法?

不,你可以连接一些奇怪的泛型——Foo<T extends Foo>或类似的——但它不会很令人满意。

基本上,“这种类型”需要一些语言支持,其中该类型的唯一有效表达式是nulland this。那不存在,所以你只剩下覆盖了:

public Bar setTitle(String title) {
    super.setTitle(title);
    return this;
}

或者:

public Bar setTitle(String title) {
    return (Bar) super.setTitle(title);
}

这只是继承最终成为痛苦的情况之一:(

于 2012-11-11T16:39:31.410 回答
2

我确实尝试过使用泛型...

public class Foo<T extends Foo> {

    public T setTitle(String title){
        .....
        return (T) this;
    }
}

public class Bar extends Foo<Bar>{

    /* OTHER STUFF */
}

似乎工作。

于 2012-11-11T16:41:11.247 回答
1

我认为它的实际返回Bar只有。只需进行类型转换以引用对象,Bar如下所示:

    Bar bar = (Bar)(new Bar().setTitle("Foo Title"));
    System.out.println(bar.getTitle());//prints Foo Title

假设getTitle()方法存在于Foo返回标题中。

如果您添加另一个方法,例如getBarTitleBar类中:

      public String getBarTitle(){
          return getTitle()+" of Bar";
      }

然后

  System.out.println(bar.getBarTitle());//prints Foo Title of Bar

说明: 当您调用setTitleon 时new Bar(),该方法在BarObject 上调用并且this表示Bar对象 not Foo,因此它Bar仅返回类类型 as 的 onject Foo,这是超类。在这个过程中,它不会改变原来的类类型,它根本是 bar, 因此类型转换应该为你服务。

于 2012-11-11T16:41:16.817 回答
1

您可以使用具有上限的泛型:

public class Foo<T extends Foo<T>> {
    public T setTitle() {
        ...
        return (T) this;
    }
}

public class Bar extends Foo<Bar> {
    ....
}
于 2012-11-11T16:43:59.073 回答
1

准确地说,它不返回 Foo 引用,而是返回 Bar 引用,您可以使用 System.out.println(reference.getClass().getName()) 进行检查。

写的时候也一样,

List l=new ArrayList(); 

(忘记 LIst 是一个接口,这是题外话)

l实际上是对 ArrayList 的引用,即使此信息是“隐藏的”,但调用 l.someMathod() 会调用 ArrayList 方法,而不是 List 方法——这就是面向对象的工作原理!

于 2012-11-11T16:46:06.230 回答