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

问题描述

我有一个名为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

解决方法

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

public Seat() {
}
,

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

,

问题是,在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)
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...