public class OverloadTest {

    public static void main(String ar[]){
         OverloadTest t = new OverloadTest();
         t.add(5,5);
    }

    // 1st method
    public void add(int i , int j){
         System.out.println("In Primitive type" + (i+j))
    }

    // 2nd method
    public void add(Integer i , Integer j){
         System.out.println("In Object type" + (i+j))
    }

}

This code works perfectly. I want to understand should not there a compile time error as 5 will be autoboxed to an Integer Object (Integer.valueOf(5)) and should choose 2nd Method. Why there is no compile time error ?

有帮助吗?

解决方案

Why would you expect there to be autoboxing? When searching for an appropriate method, the compiler first checks to see if there are applicable methods for the plain int types. Only if such a method is not found does autoboxing come into play.

This process is described in the JLS §18.5.1.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top