我想从基类继承一个语法流畅的方法:

class BaseModel {
      int count;

      public BaseModel setCount(int value){
           this.count=value;
           return this;
      }
}


class FooModel extends BaseModel{
      int age;

      public FooModel setAge(int value){
           this.age=value;
           return this;
      }
}

此代码的问题在于:
FooModel model= new FooModel().setCount(2).setAge(25);

使编译器抱怨,因为setCount方法返回类型是BaseModel而不是FooModel
是否有某种方法可以在父类中声明该方法,以便子类返回正确的类型,而不必在每个子类中手动重写该方法?
class FooModel extends BaseModel{
      int age;

      public FooModel setAge(int value){
           this.age=value;
           return this;
      }

      @Override
      public FooModel setCount(int value){
           super.setCount(value);
           return this;
      }
}

谢谢

最佳答案

我看到的唯一方法是使用泛型:

class BaseModel<T> {
    int count;

    public T setCount(int value) {
        this.count = value;
        return (T) this;
    }
}

class FooModel extends BaseModel<FooModel> {
    int age;

    public FooModel setAge(int value) {
        this.age = value;
        return this;
    }
}

通过这个,您可以编写所需的代码片段
FooModel model = new FooModel().setCount(2).setAge(25);

09-19 12:02