Q. When ambiguity exists between method calls, how does compiler resolve it? Why String version of the method is called instead of the Object version in the following example?
// Overloading.java
//*******************************
public class Overloading {
public void method(Object o) {
System.out.println("Object Version");
}
// String is an Object, but a specific Object
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
Overloading test = new Overloading();
// null is ambiguous to both methods
// The more specific one is called
test.method(null); // String Version
}
}
//*******************************
A:
The answer is in the comments of above code, just remember that when ambiguity exists between method calls, compiler resolves it by choosing the more specific ones. If it does not work, it will error out.
重載調用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
static 和 interface的關係
static 和 interface的關係:1)內部接口是隱式的靜態的,不管你是不是用static來修飾注意:內部接口很少用到2)外部接口不能是靜態的
happyzhm5
2020-06-25 22:36:57
初始化順序(Thinking in Java中的一段有意思的例子)
abstract class Glyph { abstract void draw(); Glyph() { System.out.prin
happyzhm5
2020-06-25 22:36:57
Can inner class extends outer class, or opposite?
happyzhm5
2020-02-25 15:57:58
if the reference of the thread is set to null.
happyzhm5
2020-02-25 15:57:58
In what situation, an IllegalThreadStateException will be thrown?
happyzhm5
2020-02-25 15:57:58
Constructor or not constructor?
happyzhm5
2020-02-25 15:57:58
Why this code compile OK, but throw ClassCastException at run time?
happyzhm5
2020-02-25 15:57:58
Can one object access a private variable?
happyzhm5
2020-02-25 15:57:58
abstract method Graphics.drawString()?
happyzhm5
2020-02-25 15:57:58
關於線程同步的一點心得
happyzhm5
2018-08-31 04:31:24
left-to-right evaluation rule and side effect
happyzhm5
2018-08-31 04:31:22
Java同步機制淺談――synchronized對代碼作何影響?
happyzhm5
2018-08-31 04:31:20
丟失的違例(小心你的finally)
happyzhm5
2018-08-31 04:31:20
24小時熱門文章