简体   繁体   English

基本类型和对象类型的方法重载

[英]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. 我想了解应该不会出现编译时错误,因为5将自动装箱到一个Integer对象(Integer.valueOf(5)),并且应该选择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. 在搜索适当的方法时,编译器首先检查是否存在适用于纯int类型的方法。 Only if such a method is not found does autoboxing come into play. 只有找不到这种方法,自动装箱才会起作用。

This process is described in the JLS §18.5.1 . JLS§18.5.1中描述了此过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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