创建空子类构造函数

时间:2018-05-04 16:14:22

标签: java class inheritance constructor

public class Monitor extends Peripheral {
    public Monitor(){
        super();
    }
    public Monitor (String name,String maker, int age, int price,String type,int size,String res,String ports){
        super(name,maker,age,price);
        this.type = typel
        this.size = size;
        this.res = res;
        this.ports = ports;
    }
}

这是子类。我想创建它以便我可以创建一个监视器对象而不给它任何参数。这些是其父母的类别:

public class Product {
    protected String name, maker;
    protected int age,price;
    public Product(){}
    public Product(String name,String maker, int age, int price){
        this.name = name;
        this.maker = maker;
        this.age = age;
        this.price = price;
    }
}
public class Peripheral extends Product {
    //basically nothing here
    private static double discount = 0;
    public static void setDiscount(double disc){
        discount = disc;
    }
    public static double getDiscount(){
        return discount;
    }
}

编译器说:error:constructor类Peripheral中的Peripheral不能适用于给定的类型;                   超(); required:String,String,int,int 发现:没有参数

3 个答案:

答案 0 :(得分:0)

没有带外设参数的构造函数!

Peripheral(String name, String maker, int age, int price)

答案 1 :(得分:0)

来自Peripheral

Product does not inherit constructor,您需要明确声明:

public class Peripheral extends Product {

    public Peripheral(String name,String maker, int age, int price) {
        super(name,maker,age,price);
    } 

    //....
}

答案 2 :(得分:0)

首先,你有一个拼写错误:

public Monitor (String name,String maker, int age, int price,String type,int 
size,String res,String ports){
    super(name,maker,age,price);
    this.type = typel <--- here(nasty semi-colons)

我认为您必须在监视器对象之前强制创建一个产品对象,因为您将缺少监视器试图获取的超级参数。

解决方法是,您可能想要创建另一个没有超级(params)的构造函数;这样就可以摆脱你所得到的错误。

所以代替你的构造函数,你应该做这样的事情:

public Monitor (String type,int size,String res,String ports){
    this.type = type;
    this.size = size;
    this.res = res;
    this.ports = ports;
}

希望这能解决你的问题!