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)
}
座位.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
解决方案
问题是,在 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)
}
推荐阅读
- excel - Excel 公式在尝试计算加班时间或更短时间时不起作用
- cypress - cy.fixture 不在循环内执行
- c# - if 语句在 void Start(); 中单独工作;
- .net - Fluentvalidation 规则未通过 MicroElements 库反映在 Swagger 中
- json - 如何使用asp.net mvc中的web api从服务Angular 12调用方法到REST
- node.js - 回压后无法处理 iFrame 中的响应
- javascript - 仅重新渲染特定的孩子
- angular - 将模型和输入值相乘
- apache-flink - 表级别的 Flink TTL
- java - 使用 geckoddriver 时出错:发现意外的参数“--websocket-port”