有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

共 (3) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    问题是,在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)
    }
    
    
  3. # 3 楼答案

    您正在调用super(),而您没有不接受参数的默认构造函数。 因此,添加下面的构造函数,它就会工作。或者在super(param, param)调用中添加所需的参数

    public Seat() {
    }