混亂比方說,我們有這兩個階級,一個主要的方法:約上溯造型和重載方法
public class Super {
public void f(double d){
System.out.println("Super: f(double d)");
}
public void f(int i){
System.out.println("Super: f(int i)");
}
}
public class Sub extends Super {
public void f(double d){
System.out.println("Sub: f(double d)");
}
public void f(float f){
System.out.println("Sub: f(float f)");
}
}
public class M {
public static void main(String[] args){
Sub a = new Sub();
a.f(1.5f); //output: "Sub: f(float f)"
Super b = new Sub();
b.f(1.5f); //output: "Sub: f(double d)"
}
}
爲什麼第二個電話會導致Sub: f(double d)
而不是像Sub: f(float f)
的第一個?
當我添加
public void f(float f) {
System.out.println("Super: f(float f)");
}
到Super
類,則輸出變爲Sub: f(float f)
。
鑑於這種行爲,我希望的工作流程是這樣的:
- 作爲
a
被upcasted到Super
,類Super
檢查的匹配方法 - 只有
public void f(double d)
被發現,所以浮子澆鑄到一個雙 - 現在方法
public void f(double d)
在更具體的類Sub
看出並執行
這是正確的嗎?
因爲沒有方法'f(float)'可以通過'Super'類型的引用獲得。 – 2014-12-06 21:01:15