gpt4 book ai didi

java - No suitable constructor found 错误发生在扩展子类构造函数中

转载 作者:行者123 更新时间:2023-11-30 07:01:29 28 4
gpt4 key购买 nike

我最近一直在做一个项目,在这个项目中我最终使用了一个扩展另一个类(即连接和传输)的类。我收到的错误是“错误:没有找到适合 Connection 的构造函数(无参数)”。错误是在 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;
}

这基本上是在主类的实例变量 hashmap 中找到您要查找的站点。

最佳答案

由于 Transfer 扩展了 Connection,当构造 Transfer 时,必须在构造之前调用 Connection 的构造函数连接 可以继续。默认情况下,Java 将使用无参数构造函数(如果存在)。但是,Connection 没有无参数构造函数(因为您显式定义了一个构造函数,然后没有显式定义无参数构造函数)因此您必须显式指定 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 */
}
}

这就是您为基类显式调用构造函数的方式。

关于java - No suitable constructor found 错误发生在扩展子类构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785693/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com