编程语言
首页 > 编程语言> > java – 在方法重写中返回继承的类而不是超类

java – 在方法重写中返回继承的类而不是超类

作者:互联网

我有一个看起来像这样的类结构:

class Parent {
    public Parent(int property) { /* use property */}
}
class Son extends Parent {
    public Son(int parentProperty, String sonProperty) { 
        super(parentProperty);
        /* use son property */ 
    }
}

我想为这两个类创建构建器,以便:

class ParentBuilder {
    protected int parentProperty;

    public ParentBuilder parentProperty(int parentPropertyValue) {
        parentPropertyValue = parentPropertyValue;
        return this;
    }

    public Parent build() {
        return new Parent(parentProperty);
    }
}
class SonBuilder extends ParentBuilder {
    private String sonProperty;

    public SonBuilder sonProperty(String sonProperty) {
        this.sonProperty = sonProperty;
        return this;
    }

    @Override
    public Son build() {
        return new Son(parentProperty, sonProperty);
    }
}

但这会导致以下问题:

SonBuilder sonBuilder = new SonBuilder();
sonBuilder.sonProperty("aString").build(); // this works and creates Son
sonBuilder.sonProperty("aString").parentProperty(1).build(); // this works and creates Parent instead of Son
sonBuilder.parentProperty(1).sonProperty("aString").build(); // this doesn't work

我知道我在挑剔,这可以通过不返回这个来解决(即没有方法链接),但我想知道是否有一个优雅的解决方案.

编辑

似乎“优雅”这个词有点混乱.

“优雅”是指一种允许方法链接而不涉及铸造的解决方案.

解决方法:

第一点

sonBuilder.sonProperty("aString").parentProperty(1).build();

this works and creates Parent instead of Son

期望parentProperty()返回ParentBuilder:

public ParentBuilder parentProperty(int parentPropertyValue) {...

ParentBuilder.build()创建一个Parent:

public Parent build() {
    return new Parent(parentProperty);
}

第二点

sonBuilder.parentProperty(1).sonProperty("aString").build(); // this doesn't work

如第一点所述,parentProperty()返回一个ParentBuilder.
而ParentBuilder当然没有sonProperty()方法.
所以它无法编译.

I’m wondering if there is an elegant solution.

优雅的解决方案不是让SonBuilder继承ParentBuilder,而是使用ParentBuilder字段.
例如 :

class SonBuilder {

    private String sonProperty;
    private ParentBuilder parentBuilder = new ParentBuilder();

    public SonBuilder sonProperty(String sonProperty) {
      this.sonProperty = sonProperty;
      return this;
    }

    public SonBuilder parentProperty(int parentPropertyValue) {
      parentBuilder.parentProperty(parentPropertyValue);
      return this;
    }

    public Son build() {
      return new Son(parentBuilder.parentProperty, sonProperty);
    }
}

你可以这样创造儿子:

SonBuilder sonBuilder = new SonBuilder();
Son son = sonBuilder.sonProperty("aString").parentProperty(1).build();

标签:java,inheritance,builder,fluent,method-overriding
来源: https://codeday.me/bug/20190608/1195745.html