为什么编译器尝试宽和盒子为什么不Box和宽?

Gur*_*lki 2 java

在调用特定方法时,我读到Wide和Box是首选,为什么不是Box和Wide.任何人都可以用一个小例子解释我的原因.

Oli*_*ier 7

加宽:调用参数类型较窄的方法.

public class Test {
    static void doIt(long l) { }
    public static void main(String[] args) {
        int i = 1;
        doIt(i); // OK: int i is widened to long
    }
}
Run Code Online (Sandbox Code Playgroud)

Boxing:调用一个带有原始参数的包装器类型的方法.

public class Test {
    static void doIt(Integer i) { }
    public static void main(String[] args) {
        int i = 1;
        doIt(i); // OK: int i is boxed to Integer
    }
}
Run Code Online (Sandbox Code Playgroud)

加宽然后拳击:不起作用.

public class Test {
    static void doIt(Long l) { }
    public static void main(String[] args) {
        int i = 1;
        doIt(i); // FAILS. Cannot widen int to long and then box to Long
    }
}
Run Code Online (Sandbox Code Playgroud)

拳击,然后扩大:只有扩大到超类型才有效.

public class Test {
    static void doIt(Number n) { }
    static void go(Long l) { }
    public static void main(String[] args) {
        int i = 1;
        doIt(i); // OK. i is boxed to Integer, and Number is a supertype of Integer
        go(i); // FAILS: Long is not a supertype of Integer
    }
}
Run Code Online (Sandbox Code Playgroud)