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

时间:2010-01-25 16:21:31

标签: java

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

3 个答案:

答案 0 :(得分: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
    }
}

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
    }
}

加宽然后装箱:不起作用。

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
    }
}

拳击然后加宽:只有在扩大到超类型时才有效。

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
    }
}

答案 1 :(得分:2)

答案很简单:你只能拓宽基元。因此,编译器必须在它之前加宽。

答案 2 :(得分:0)

从SCJP学习资料我可以告诉你:

调用方法时,将按此顺序检查以下内容,如果找到匹配项,则会调用相应的方法:

1) Widening (preferred: 1st option to be chosen)
2) Boxing
3) Var args

这就是它的工作方式!记住订单!