【发布时间】: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 模式来允许在父级和子级的其他成员中定义公共成员?
【问题讨论】:
-
返回
ParentBuilder的是age,因此在尝试调用height时会出现编译错误。查看stackoverflow.com/questions/21086417/… 或stackoverflow.com/questions/17164375/… -
我只会使用
Integer而不是int如果 a) 值可以是null或 b) 你别无选择 -
这里没有inner-classes,只有静态嵌套类,根据定义它们不是内部的。
标签: java inheritance