質問

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