开发者

Why compiler tries to Wide and Box Why not Box and Wide?

When invoking a particular method开发者_开发技巧, I read that Wide and Box is preferred, why not Box and Wide. can anyone explain me why with one small example.


Widening: calling a method with a narrower parameter type.

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: calling a method that takes a wrapper type with a primitive argument.

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

Widening and then boxing: doesn't work.

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

Boxing and then widening: only works if widening to a supertype.

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


The answer is fairly simple: You can only widen primitives. Therefore, the compiler must widen before it boxes.


From the SCJP Study Material i can tell you this:

When a method is called the following will be checked in this order and if a match is found the appropriate method will be called:

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

It's just the way it works! Mind the order !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜