java如何初始化父类类型的数组?
我有一个名为SeatingPlan
的类,它继承自Seat
在SeatingPlan
构造函数中,我将初始化为:
public SeatingPlan(int numberOfRows, int numberOfColumns) {
super();
rows = numberOfRows;
columns = numberOfColumns;
seats = new Seat[rows][columns]; // (Seat [][] seats during variable declarations)
}
座位。爪哇:
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
# 1 楼答案
您需要为Seat使用默认的空构造函数,或者需要使用参数super(subject,number)调用super
# 2 楼答案
问题是,在Java中,当您重载构造函数时,编译器将不再自动提供默认构造函数。因此,如果您仍然需要使用它,那么您需要在类中定义它
现在,您可以通过SeatingPlan子类访问父类Seat的no-args构造函数
# 3 楼答案
您正在调用
super()
,而您没有不接受参数的默认构造函数。 因此,添加下面的构造函数,它就会工作。或者在super(param, param)
调用中添加所需的参数