什么是“构造函数...是模棱两可的“的意思?

2022-09-01 18:23:01

我想知道Eclipse中的错误消息是什么意思:

构造函数 Case(Problem, Solution, double, CaseSource) 是模棱两可的


答案 1

当您尝试实例化可应用于多个构造函数的类时,存在此问题。

例如:

public Example(String name) {
    this.name = name;
}

public Example(SomeOther other) {
    this.other = other;
} 

如果使用 String 对象调用构造函数,则有一个确定的构造函数。但是,如果您实例化,那么它可以应用于任何一个,因此是模棱两可的。new Example(null)

这同样适用于具有相似签名的方法。


答案 2

为了增加其他答案,可以通过将论点转换为预期来避免,例如:

class Foo {

    public Foo(String bar) {}
    public Foo(Integer bar) {}

    public static void main(String[] args) {
        new Foo((String) null);
    }

}

推荐