开发者

What is the explanation of this java code?

开发者 https://www.devze.com 2023-01-03 03:12 出处:网络
I have the following code : public class Main { public void method(Object o) { System.out.println(\"Object Version\");

I have the following code :

public class Main {
     public void method(Object o)
     {
           System.out.println("Object Version");
     }
     public void method(String s)
     {
          System.out.println("String Version");
     }
     public static void main(String args[])
     {
           Main question = new Main();
           questi开发者_Go百科on.method(null);//1
     }
}

why is the result is "String Version" ? and why there is a compiler error if the first method takes a StringBuffer object ?

Another case : if the first method takes a StringBuffer object and I write question.method("word");the result will be "String Version" . Why ? why there is no compiler error ?


The JAVA spec says that in cases like this, the most specific function will be called. Since String is a sub type of Object - the second method will be called. If you change Object to StringBuffer - there is no specific method since StringBuffer is not a sub type of String and vice versa. In this case the compiler does not know which method to call - hence the error.


When looking at the other case :

package com.snamellit;

public class Main {
    public void method(Object o) {
        System.out.println("Object Version");
    }

    public void method(String s) {
        System.out.println("String Version");
    }

    public static void main(String args[]) {
        Main question = new Main();
        question.method("word");
    }
}

If the first method tqkes a StringBuffer and the second a String, there is no confusion possible as "word" is a String and not a StringBuffer.

In Java the identity of a function/method is dependent on 3 things : the name, the type pf the parameters (aka the argument signature) and the classloader. Since both types have a different argument signature the compiler can easily choose the right one and does not raise an error.

0

精彩评论

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