【发布时间】:2014-04-27 17:17:39
【问题描述】:
class Test {
public Test(Object obj) {
System.out.println("Object");
}
public Test(String s) {
System.out.println("String");
}
public static void main(String[] args) {
new Test(null); //prints String. Why not Object?
}
}
如果我添加另一个参数类型为 Integer 的构造函数,或者,对于任何其他类型,调用 new Test(null); 会导致编译错误 - The constructor Test(Object) is ambiguous。
为什么上面的例子没有产生错误?在执行它时,会调用带有参数String 的构造函数。为什么不调用参数类型为Object 的构造函数?这种歧义是如何解决的?
【问题讨论】:
标签: java constructor