【问题标题】:No suitable constructor found error occuring inside extended subclass Constructors在扩展子类构造函数中未找到合适的构造函数
【发布时间】:2015-04-22 00:40:38
【问题描述】:

我最近一直在从事一个项目,在该项目中我最终使用了一个扩展另一个类(即连接和传输)的类。我收到的错误是“错误:找不到适合连接的构造函数(无参数)。”错误出现在 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中找到了你要找的站。

【问题讨论】:

    标签: java class constructor


    【解决方案1】:

    由于Transfer 扩展Connection,当Transfer 被构造时,Connection 的构造函数必须在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 */
        }
      }
    

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

    【讨论】:

    • 因此您必须先将对象创建为 Connection,然后才能将其设为专用类型:Transfer。这是正确的推理吗?
    • @MLavrentyev 人们通常是这样想的,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2020-10-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多