首页 > 解决方案 > 如何初始化父类类型的数组?

问题描述

我有一个名为的类SeatingPlan,它继承自Seat.

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

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

座位.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

标签: javaobject-oriented-analysis

解决方案


问题是,在 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 的无参数构造函数。

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)
}


推荐阅读