Search code examples
javaoverloadingscjp

Java Method Overloading with Boxing/Widening


I am working on Java Se 7 OCA and could not figure out why below code does not compile. aMethod call in main method gives compile error stating ambiguous method. Precedence rules between widening and boxing seems to clash in this overloading method sample.

public class Overloading {
public static void main(String[] args) {
    Byte i = 5;
    byte k = 5;
    aMethod(i, k);
}

static void aMethod(byte i, Byte k) {
    System.out.println("Inside 1");
}

static void aMethod(byte i, int k) {
    System.out.println("Inside 2");
}

static void aMethod(Byte i, Byte k) {
    System.out.println("Inside 3 ");
}
}

The error is "The method aMethod(byte, Byte) is ambiguous for the type Overloading". when I comment out first method, it gives same error for second method.

My thinking is: First method needs unboxing and boxing Second method needs unboxing and widening Third method needs only boxing. So it must be third method, since it needs the least conversion and all of them have boxing conversion.


Solution

  • The problem is with all these methods:

    static void aMethod(byte i, Byte k) {
        System.out.println("Inside 1");
    }
    
    static void aMethod(byte i, int k) {
        System.out.println("Inside 2");
    }
    
    static void aMethod(Byte i, Byte k) {
        System.out.println("Inside 3 ");
    }
    

    Java doesn't know, which one it should invoke in line:

        aMethod(i, k);
    

    Your params i and k could be converted by various ways, according to JLS specifications:

    i could be unboxed to byte (5.1.8) or leaved as Byte (5.1.1) -> 2 variants

    k could be boxed into Byte (5.1.7) or widened to int type (5.1.2) -> 2 variants.