我正在阅读这篇关于子类化构建器类的文章。我理解这篇文章,但有一点让我感到困扰。有这个方法,
public static Builder<?> builder() {
return new Builder2();
}
当我更改Builder<?>
为Builder
原始类型时,编译器不会编译代码。错误是,
Rectangle.java:33: error: cannot find symbol
System.out.println(Rectangle.builder().opacity(0.5).height(250);
使用附加传递给编译器的附加信息是什么<?>
?我怀疑是编译器在编译过程中无法找到正确的实例。如果我删除 (A) 中的注释标记,则代码编译并运行良好。它一直指的是 Rectangle 实例。所以,我的猜测是编译器失败了。
如果有人可以向我指出一篇解释这一点或导致找到更多信息的文章,那就太好了。谢谢。
我在这里粘贴了代码:
public class Shape {
private final double opacity;
public static class Builder<T extends Builder<T>> {
private double opacity;
public T opacity(double opacity) {
this.opacity = opacity;
return self();
}
/* Remove comment markers to make compilation works (A)
public T height(double height) {
System.out.println("height not set");
return self();
}
*/
protected T self() {
System.out.println("shape.self -> " + this);
return (T) this;
}
public Shape build() {
return new Shape(this);
}
}
public static Builder<?> builder() {
return new Builder();
}
protected Shape(Builder builder) {
this.opacity = builder.opacity;
}
}
public class Rectangle extends Shape {
private final double height;
public static class Builder<T extends Builder<T>> extends Shape.Builder<T> {
private double height;
public T height(double height) {
System.out.println("height is set");
this.height = height;
return self();
}
public Rectangle build() {
return new Rectangle(this);
}
}
public static Builder<?> builder() {
return new Builder();
}
protected Rectangle(Builder builder) {
super(builder);
this.height = builder.height;
}
public static void main(String[] args) {
Rectangle r = Rectangle.builder().opacity(0.5).height(250).build();
}
}