我在用Java泛型正确设置此模式时遇到问题,或者根本无法使用。我想有2个抽象类和一个普通的抽象类。 每个子类都将自己的参数带到类中。从我的观点看来,我搞砸了泛型,但是我不知道在哪里。
public abstract class First {
private final long id;
First(Builder<?> builder) {
this.id = builder.getId();
}
public static abstract class Builder<T extends Builder<T>> {
@Getter long id;
public abstract First build();
public T setID(long id) {
this.id = id;
return (T)self();
}
protected abstract T self();
}
秒:
public abstract class Second extends First {
Second(Builder<?> builder) {
super(builder);
}
public static abstract class Builder<T extends Builder<T>> extends First.Builder {
public T print() {
System.out.println("hi");
return (T) self();
}
}
}
第三个:
public class Third extends Second {
private Third(Builder builder) {
super(builder);
}
public static class Builder<T extends Builder<T>> extends Second.Builder {
public Third build() {
return new Third(this);
}
@Override
protected Builder self() {
return this;
}
}
}
我的问题是,我可以打电话给
new Third.Builder()
.print()
.setID(1)
.build();
但不是:
new Third.Builder()
.setID(1)
.print()
.build();
java给了我
Error:(13, 17) java: cannot find symbol
symbol: method print()
location: class blub.First.Builder