Method overloading with primitives and their wrappers
Asked Answered
F

2

16

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.");
    }
}
Fallow answered 14/1, 2015 at 10:7 Comment(0)
F
19

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.

Ferrate answered 14/1, 2015 at 10:11 Comment(2)
Can you explain how primitive type can be mapped to Object class as primitive type super class is null and not Object, then how it maps to method call taking Object as parameter.Meticulous
It is first converted to an object by the autoboxing transformation.Ferrate
H
-4

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.

Henricks answered 14/1, 2015 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.