我想从包含Builder类的Parent类继承一个类,但是在父类中出现编译错误“默认构造函数不可用”。
我尝试为具有空值的父类构建默认构造函数。但是根本没有调用默认构造函数,它会将所有值初始化为null。
包装产品; 公共类产品{
private final String id; //required
private final String description; //required
private final double price; //required
public enum Category{
Electronics,
Clothing,
ShowCart
}
private Products(ProductBuilder builder) {
this.id = builder.id;
this.description = builder.description;
this.price = builder.price;
}
public String getID() {
return id;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public static class ProductBuilder {
private final String id; //required
private final String description; //required
private final double price; //required
public ProductBuilder(String id, String description, double price)
{
this.id = id;
this.description = description;
this.price = price;
}
public Products build(){
Products prod = new Products(this);
return prod;
}
}
}
包装产品;
公共类电子产品扩展产品{//编译错误
//DEFAULT CONSTRUCTOR NOT AVAILABLE
}
我想在不引入默认构造函数的情况下解决问题,也不要违反BUILDER PATTERN
答案 0 :(得分:0)
您需要向Electronic添加一个构造函数,并且必须为其基类调用该构造函数。这是Java中继承类的标准过程。
public class Electronic extends Products {
public Electronic(ProductBuilder builder) {
super(builder);
}
}
如果这没有意义,请问自己:基类需要一个ProductBuilder。没有这个新的构造函数,基类如何获得其ProductBuilder?