这只是一个练习,但我无法弄清楚这种模糊性:
private static void flipFlop(String str, int i, Integer iRef) {
System.out.println(str + "ciao");
}
private static void flipFlop(String str, int i, int j) {
System.out.println(str + "hello");
}
public static void main(String[] args) {
flipFlop("hello", new Integer(4), 2004);
}
Run Code Online (Sandbox Code Playgroud)
它说:
对于类型Test,方法flipFlop(String,int,Integer)是不明确的
我猜想第二个参数将被解包为int,所以第二个flipFlop方法就是选择.
我刚刚写了一些具有以下结构的代码:
public void method(int x) {
//...
}
public void method(int x, String... things) {
//...
}
Run Code Online (Sandbox Code Playgroud)
我很惊讶这编译了,如果我调用的话
method(3);
Run Code Online (Sandbox Code Playgroud)
然后它会选择第一个.显然,这在某种意义上是自然选择的,但如果第一种方法不存在,这将是调用第二种方法的合理方式(使用空的varargs数组).所以它应该被认为是模糊的并产生编译时错误?
或者这被视为特例?
这样对待它似乎是错误的,因为这意味着添加新方法可能会破坏现有代码,这不是一个非常幸福的事态.
(Goodness只知道如果第一个被添加为包含第二个子类的子类的新方法,你最终会调用哪个...)
请解释一下,为什么当我编写 4 个重载方法并调用它时 => 它选择以“int”为默认值的方法,而不是“byte”,后者更接近/更好,因为它可以存储从 -127 到 128 的值?
class Main {
public static void method(short s) {
System.out.println("short");
}
public static void method(byte b) {
System.out.println("byte");
}
public static void method(int i) {
System.out.println("int");
}
public static void method(long l) {
System.out.println("long");
}
public static void main(String[] args) {
// put your code here
method(10);
}
}
Run Code Online (Sandbox Code Playgroud)