如何初始化父类类型的数组?

时间:2020-10-20 13:57:23

标签: java object-oriented-analysis

我有一个名为SeatingPlan的类,它是从Seat继承的。

SeatingPlan构造函数中,我初始化为:

public SeatingPlan(int numberOfRows, int numberOfColumns) {
   super();
   rows = numberOfRows;
   columns = numberOfColumns;
   seats = new Seat[rows][columns];  // (Seat [][] seats during variable declarations)
}

Seat.java:

public Seat(String subject, int number) {
   courseSubject = subject;
   courseNumber = number;
}

但是我遇到此错误:

SeatingPlan.java:8: error: 
    constructor Seat in class Seat cannot be applied to given types;
        super();
        ^
      required: String,int
      found: no arguments
      reason: actual and formal argument lists differ in length
    1 error
    [ERROR] did not compile; check the compiler stack trace field for more info

3 个答案:

答案 0 :(得分:0)

您正在调用super(),但没有默认构造函数不接受参数。 因此,添加以下构造函数,它将起作用。或在super(param, param)调用中添加所需的参数。

public Seat() {
}

答案 1 :(得分:0)

您需要为Seat提供默认的空构造函数,或者需要使用参数super(subject,number)调用super

答案 2 :(得分:0)

问题是,在Java中,当您重载构造函数时,编译器将不再自动提供默认构造函数。因此,如果仍然需要使用它,则需要在您的类中定义它。

public class Seat{

    public Seat(){//Implement the no-arg constructor in your class


    }

    public Seat(String subject, int number) {
       courseSubject = subject;
       courseNumber = number;
    }

}

现在您可以通过SeatingPlan子类访问父类Seat的no-args构造函数。

public SeatingPlan(int numberOfRows, int numberOfColumns) {
   super();//Now you can access the no-args constructor of Seat parent class
   rows = numberOfRows;
   columns = numberOfColumns;
   seats = new Seat[rows][columns];  // (Seat [][] seats during variable declarations)
}