Method overloading in java regarding arguments with int/long and String/object

好久不见. 提交于 2019-12-29 02:09:24

问题


For the following program why the methods with int and String arguments are getting called instead of long and Object?

Wanted to know why the compiler is choosing int over long and String over Object arguments.

Note: This was asked in an interview.

public class MethodOverloadingTest {

    public static void add(int n, int m){
        System.out.println("Int method");
        System.out.println(n+m);
    }

    public static void add(long n, long m){
        System.out.println("Long method");
        System.out.println(n+m);
    }

    public static void method(String st){
        System.out.println("from String method");
    }

    public static void method(Object obj){
        System.out.println("from Object method");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        add(2,3);
        method(null);
    }

}

回答1:


For the add(2,3) method, you are passing integers, that's why integers are getting called. For method(null), the most specific method argument is chosen. In this case, String is more specific than Object. Hence method(String st); gets called.




回答2:


Its simple because Java treats number by default as int and letters as string object , not as generic objects .

so when you pass add(2,3) , its taking the arguments as the normal int

to call the add(long , long) pass the arguments as ; add(2.0,4.0) something like this . and for calling the function method(object)

1.first typecast your string to type object String str; str= (object) "Hello world";

2.and then pass to method(str);




回答3:


The concept is called as Early Binding. Most specific method (based on arguments) is Chosen at compile time.

Object is the least specific than any other class in java, Since it is the super class of all.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

How it chooses is given in rule set, Specified here

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5



来源:https://stackoverflow.com/questions/20699306/method-overloading-in-java-regarding-arguments-with-int-long-and-string-object

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