int compute(String s1, Object... others)
当你打电话时会更具体compute("hi",y,y)
, since String
是对象的子类。
int compute(Object o1, Object o2, Object... others)
is the only匹配compute(y,y,y)
因为第二个方法接收 String 作为第一个参数,并且JLS15Test
不是 的子类String
EDIT
我的答案基于特定方法的基础知识,但您的代码只能编译,因为编译器能够以上述方式区分方法。
由于含糊不清,以下示例甚至无法编译:
case 1:
int compute(Object o1, Object o2, Object... others) { return 1; }
int compute(Object s1, Object... others) { return 2; }
public static void main(String[] args)
{
JLS15Test y = new JLS15Test();
System.out.println(y.compute(y,y,y));
System.out.println(y.compute("hi",y,y));
}
case 2:
int compute(String o1, Object o2, Object... others) { return 1; }
int compute(Object s1, String... others) { return 2; }
public static void main(String[] args)
{
JLS15Test y = new JLS15Test();
System.out.println(y.compute("hi","hi","hi"));
}
更多 编辑
前两次我没有很好地回答你的问题(我希望这次我能回答:))。
您正在谈论的实际案例将如下所示:
public class Test {
public static void main(String[] args)
{
Test t = new Test();
int a = t.compute("t", new Test());
System.out.println(a);
}
int compute(String s, Object... others) { return 1; }
int compute(Object s1, Object others) { return 2; }
}
在这种情况下,compute(Object s1, Object others)
那么确实更具体compute(String s, Object... others)
(参数较少)所以输出将是2
indeed.