开发者

why primitive type will call first rather than wrapper classes?

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();
 开发者_C百科      a.test(5);
   }


}

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?

Thanks,


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜