Frage

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" ?

War es hilfreich?

Lösung

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.

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top