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

No suitable constructor found error occuring inside extended subclass Constructors

我最近一直在做一个项目,在这个项目中我最终使用了一个 class,它扩展了另一个 class(即连接和传输)。我收到的错误是 "error: no suitable constructor found for Connection(no arguments)." 错误出现在 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 */
    }

}

在我的主要 class 中,我有几个使用这些函数的函数。如果除此功能外的所有功能都被注释掉,我会继续收到相同的错误:

public static Station findInStations(int iD) {      
    for(Entry<Integer, Station> stat : stations.entrySet()) {
        if(stat.getValue().id == iD) { 
            return stat.getValue();
        }
    }
    return null;
}

这样基本上就可以在main class.

的实例变量hashmap中找到你要找的站了

由于 Transfer 扩展了 Connection,当构造 Transfer 时,必须先调用 Connection 的构造函数,然后才能继续构造 Connection。默认情况下,Java 将使用无参数构造函数(如果存在)。但是,Connection 没有无参数构造函数(因为您显式定义了一个构造函数,然后没有显式定义无参数构造函数)因此您必须显式指定 [=12= 的构造函数] 使用。

因此,你应该这样写:

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 */
    }
  }

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