简体   繁体   中英

Method Overloading for Primitive and Object types

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM