首页 > 解决方案 > 方法重载在这里如何工作?

问题描述

我有两个分别带有参数 int 和 Integer 的重载方法。当我通过传递5调用打印方法时,为什么它调用第一个打印方法。它如何识别调用哪个方法?

public class Main {

    public static void main(String[] args) {
        print(5);
    }

    static void print(int a) {
        System.out.println("Calling first print");
    }

    static void print(Integer a) {
        System.out.println("Calling second print");
    }

}

标签: java

解决方案


public class Test
{
   static void print( int a )
   {
      System.out.println( "Calling first print" );
   }

   static void print( Integer a )
   {
      System.out.println( "Calling second print" );
   }

   public static void main( String[] args )
   {
      print( 5 );
      print( new Integer(5) );
   }
}

print( 5 );将输出 Calling first print ,因为您正在传递 5 ,这是一个 premitive 。print( new Integer(5) ); 将输出 Calling second print 因为您将 5 作为整数对象传递,因此方法static void print( Integer a )具有更高的优先级。


推荐阅读