Method overloading with primitives and their wrapp

2019-01-23 14:35发布

问题:

I am trying to formulate the rules that are being used in the scenarios below. Please explain why I am getting 2 different outputs.

Scenario 1 output: I am an object.

class Test {

    public static void main (String[] args) {

        Test t = new Test(); 
        byte b_var = 10;
        t.do_the_test(b_var);
    }

    public void do_the_test(Character c) {

       System.out.println("I am a character.");
    }

    public void do_the_test(Integer i) {

      System.out.println("I am an integer.");
    }

    public void do_the_test(Object obj) {

      System.out.println("I am an object.");
    }
}

Scenario 2 output: I am an integer.

class Test {

    public static void main (String[] args) {

        Test t = new Test(); 
        byte b_var = 10;
        t.do_the_test(b_var);
    }

    public void do_the_test(char c) {

       System.out.println("I am a character.");
    }

    public void do_the_test(int i) {

      System.out.println("I am an integer.");
    }

    public void do_the_test(Object obj) {

      System.out.println("I am an object.");
    }
}

回答1:

The Java Language Specification says this about method signature resolution:

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

In your second case, the method signature involving int is applicable without autoboxing, but with a widening numeric conversion. In the first case, both the widening conversion and autoboxing would be needed to reach the Integer signature; however, Java does either autoboxing or primitive conversion, never both.



回答2:

While selecting the method, the arguments matching closest to the parameter passed is chosen.

In first case, the number value has a choice of three classes which it cannot directly map. Since Object is the superdad of all classes, it matches with fn[Object] and hence I am an object.

In second case, function call found its closest matching function with fn[integer], there by result as I am an integer.