【问题标题】:Inheritance and Static Nested Java Classes继承和静态嵌套 Java 类
【发布时间】:2017-06-22 03:13:36
【问题描述】:

我正在使用 Java 建模并使用 Builder 模式。在许多情况下,一些公共成员是在父级中定义的,而其他成员则在从父级继承的子级上。一个例子如下:

public class Parent {
    private Integer age;

    static class ParentBuilder {
        private Integer age;

        public ParentBuilder age(Integer age) {
            this.age = age;
            return this;
        }
    }
}

public class Child extends Parent {

    private Integer height;

    static class ChildBuilder extends Parent.ParentBuilder {
        private Integer height;

        public ChildBuilder height(Integer height) {
            this.height = height;
            return this;
        }

        public Child build() {
            return new Child(this);
        }
    }

    public static ChildBuilder builder() {
        return new ChildBuilder();
    }

    public Child(ChildBuilder b) {
        this.height = b.height;
    }
}

如果我尝试做类似的事情

Child child = Child.builder()
    .age(18)
    .height(150)
    .build();

我在尝试编译时遇到错误:

Main.java:6: error: cannot find symbol
        .height(150)
        ^
symbol:   method height(int)
location: class ParentBuilder

如果我删除 .height(150),我会在 .build() 上得到同样的错误。看来我对静态嵌套类的继承有一个根本的误解。

为什么,当Child.builder() 返回ChildBuilder 时,编译器会抱怨该方法不在ParentBuilder 中?有没有办法让这项工作像我尝试的那样,利用继承和这个 Builder 模式来允许在父级和子级的其他成员中定义公共成员?

【问题讨论】:

标签: java inheritance


【解决方案1】:

你可以让它与泛型一起工作

static class ParentBuilder<B extends ParentBuilder<B>> {
    public B age(Integer age) {
        this.age = age;
        return (B) this;
    }
}

static class ChildBuilder extends Parent.ParentBuilder<ChildBuilder> {
    private Integer height;

    public ChildBuilder height(Integer height) {
        this.height = height;
        return this;
    }

    public Child build() {
        return new Child(this);
    }
}

这样age 将返回ChildBuilder 以获取ChildBuilder

【讨论】:

  • 谢谢,加上@Tunaki 的链接,我想我明白了。确实需要将 this 转换为 (B) 或使用 getThis() 模式。
  • @razor 是的。你确实需要一个演员表。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
相关资源
最近更新 更多