You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xtend是否支持多构造函数?Eclipse子类构造函数调用报错咨询

关于Xtend多构造函数的问题解答

嘿,先给你吃个定心丸:Xtend完全支持多构造函数,你遇到的编译错误不是语言本身不支持,而是代码里有两个具体问题需要修正,咱们一步步来看:

问题1:第二个构造函数里的未定义变量

看你父类MatchingBase的第二个构造函数:

new (List<Integer> conn) {
    connections = new ArrayList<Integer>()
    for (int i : 0 ..< componentSize) 
        connections.add(conn.get(i))
}

这里用到的componentSize根本没定义啊!这个变量只在第一个构造函数的参数里存在,第二个构造函数没有这个入参,编译器找不到它,这是第一个报错的根源。

问题2:子类未显式调用父类对应构造函数

Xtend里,子类如果没写构造函数,默认会尝试调用父类的无参构造函数,但你的MatchingBase根本没有无参构造,只有两个带参的。所以当你调用new Permutation(new ArrayList<Integer>())时,子类默认找父类无参构造找不到,直接报编译错。

修复后的完整代码

咱们把这两个问题都改掉:

修正后的父类MatchingBase

把第二个构造函数里的componentSize换成传入列表的长度,这样就不用依赖外部变量了:

@Data 
abstract class MatchingBase implements TidilySerializable { 
    val List<Integer> connections 

    new (int componentSize) { 
        connections = (0 ..< componentSize).toList 
    } 

    new (List<Integer> conn) { 
        connections = new ArrayList<Integer>()
        // 用conn的size替代未定义的componentSize
        for (int i : 0 ..< conn.size) 
            connections.add(conn.get(i))
    } 
}

修正后的子类Permutation

给子类添加对应构造函数,显式调用父类的带List参数的构造:

@Data 
class Permutation extends MatchingBase { 
    // 显式定义构造函数,调用父类的List参数构造
    new(List<Integer> conn) {
        super(conn)
    }

    // 如果需要支持父类的第一个构造,也可以加上这个
    new(int componentSize) {
        super(componentSize)
    }
}

这样改完之后,你再调用new Permutation(new ArrayList<Integer>())就完全没问题啦~

另外补充个小知识点:Xtend的@Data注解不会在已有自定义构造的类里生成无参构造,所以父类的两个带参构造是唯一的选择,子类必须显式指定调用哪一个哦。

内容的提问来源于stack exchange,提问作者ZHU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:21:40