我最近一直在从事一个项目,在该项目中我最终使用了一个扩展另一个类(即连接和传输)的类。我收到的错误是“错误:没有找到适合连接的构造函数(无参数)”。错误出现在 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
之前调用 Connection
的构造函数连接
可以继续。默认情况下,Java 将使用无参数构造函数(如果存在)。但是,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 - 没有合适的构造函数发现扩展子类构造函数内部发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785693/