我最近一直在做一个项目,在这个项目中,我最终使用了一个扩展另一个类(即连接和传输)的类。我收到的错误是"错误:没有找到适合连接的构造函数(没有参数)"。该错误是在 Transfer 中构造函数的开头行中给出的。
class Connection {
List<Station> connectedStations = new ArrayList();
int length;
boolean isTransfer = false;
public Connection(Station s1, Station s2, int distance) {
/* Code in here */
}
public Connection(Station s1, Station s2) {
/* Code in here */
}
}
和转移:
class Transfer extends Connection {
List<Line> linesTransfer = new ArrayList();
boolean isTransfer = true;
public Transfer(Station s1, Station s2, int distance, Line l1, Line l2) {
/* Code in here */
}
public Transfer(Station s1, Station s2, Line l1, Line l2) {
/* Code in here */
}
}
在我的主课中,我有几个函数使用这些函数。如果除此函数之外的所有函数都被注释掉,我继续收到相同的错误:
public static Station findInStations(int iD) {
for(Entry<Integer, Station> stat : stations.entrySet()) {
if(stat.getValue().id == iD) {
return stat.getValue();
}
}
return null;
}
这基本上是在主类的实例变量哈希映射中找到您要查找的站。
由于Transfer
扩展了Connection
,当构造Transfer
时,必须先调用Connection
的构造函数才能继续构造Connection
。默认情况下,Java 将使用 no-args 构造函数(如果存在)。但是,Connection
没有 no-args 构造函数(因为您显式定义了构造函数,然后没有显式定义 no-args 构造函数),因此您必须显式指定要使用的 Connection
构造函数。
因此,您应该写:
class Transfer extends Connection {
List<Line> linesTransfer = new ArrayList();
boolean isTransfer = true;
public Transfer(Station s1, Station s2, int distance, Line l1, Line l2) {
super(s1, s2, distance);
/* Code in here */
}
public Transfer(Station s1, Station s2, Line l1, Line l2) {
super(s1, s2);
/* Code in here */
}
}
这就是显式调用基类构造函数的方式。