继承和静态嵌套Java类

时间:2017-02-04 22:37:26

标签: java inheritance

我正在用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模式一起使用,以允许在父项中定义普通成员,在子项中定义其他成员?

1 个答案:

答案 0 :(得分: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