문제

Alright, here's the code :

public class Dec26 {
    public static void main(String args[]) {
        short a1=6;
        new Dec26.go(a1);
        new Dec26.go(new Integer(7));
    }
    void go(Short x){System.out.println("S");}
    void go(Long x){System.out.println("L");}
    void go(int x){System.out.println("i");}
    void go(Number n){System.out.println("N");}
}

Why is the output "iN" and not "ii" ?

도움이 되었습니까?

해결책

The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

So, as there was a suitable method for Integer class, which is void go(Number n) because Number class is super class of Integer and this method accepts Integer objects as well. So compiler didn't need to unbox the Integer to int.

다른 팁

Compiler chooses the closest match without autoboxing /unboxing first. It found go(Number) and did not use unboxing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top