为什么原始类型将调用第一个而不是包装类? [英] why primitive type will call first rather than wrapper classes?

查看:93
本文介绍了为什么原始类型将调用第一个而不是包装类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A {

   public void test(Integer i) {
       System.out.println("In Wrapper Method");
   }

   public void test(int i) {
       System.out.println("In primitive Method");
   }

   public static void main(String args[]) {
       A a = new A();
       a.test(5);
   }


}

从main和pass整型参数调用测试方法,然后它将调用接受基本类型的方法作为参数。我只想知道为什么它调用原始类型方法,而不是接受包装类作为参数的方法?是否有任何规则,哪个java跟随调用方法?

When I will call test method from main and pass integer argument, then it will call the method which accept primitive type as argument. I just want to know that why it call primitive type method rather than the method who accepts wrapper class as argument? Is there any rule, which java follow to call methods?

感谢,

推荐答案

作为一个粗略的经验法则,当在不同的重载之间进行选择时,Java使用最接近的匹配方法作为参数表达式的声明类型。在这种情况下,当方法调用时, test(int i) test(Integer i) test(5),因为后者需要一个类型提升(自动加载)来使实际的参数类型正确。

As a rough "rule of thumb", Java uses the closest matching method for the declared types of the argument expressions when choosing between different overloads. In this case test(int i) is closer than test(Integer i) when the method is called as test(5), because the latter requires a type promotion (auto-boxing) to make the actual argument type correct.

事实上,决策过程比这更复杂,但是经验法则在大多数情况下都有效。

In fact the decision making process is rather more complicated than this, but the "rule of thumb" works in most cases.

这篇关于为什么原始类型将调用第一个而不是包装类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆