why primitive type will call first rather than wrapper classes?

为君一笑 提交于 2019-12-06 21:25:29

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.

In this case, you are using the literal value 5, which is a primitive int in Java. Any bare number literal such as that in Java is a primitive. To call the other method would require passing new Integer(5) instead. The autoboxing that was introduced in Java 5 can blur the lines between the two, but they are still distinct from each other.

Not really an answer, but when overloading it shouldnt matter which method is called. In this case calling either method if the value is an Integer or int the result should be the same. Overloading should only be used to convert values to some other form, or as a mechanism to provide defaults.

String.valueOf() is a good example of converting inputs to a String.

a.test(5)  // test(int i)

Compiler understands it as a primitive type. If you want run the other method you should send

a.test(new Integer(5)) // test(Integer i)

because Java select the closest matching method to run

You have passed 5 as primitive type so it will call the method that accepts primitive so if you want to call the one that accepts 5 as object then you have to first covert it to object as below

int a = 5;
Integer b = new integer(5);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!