我正在用 Java 建模并使用构建器模式。在许多情况下,一些公共(public)成员是在父级中定义的,而子级中的附加成员是从父级继承的。示例如下:
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
中?有没有办法让这项工作像我尝试的那样,利用继承和此构建器模式来允许在父级中定义公共(public)成员并在子级中定义其他成员?
最佳答案
您可以使其与泛型一起使用
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
关于java - 继承和静态嵌套 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046433/