我想知道爲什麼的Java:重載方法
z.f(-6);
在M級的呼叫是指下列函數B類:的
public void f(double y) {
this.x = (int) y + B.y;
}
,而不是在A級使用函數f,因爲bx由A覆蓋。或者使用
public void f (int y) {
this.x = y*2;
B.y = this.x;
}
在類B中,至少參數類型匹配。
完成以下代碼:
public class A {
public int x = 1;
public A(int x) {
this.x += x;
}
public A (double x) {
x += x;
}
public void f(double x) {
this.x = this.x + (int) (x + B.y);
}
}
public class B extends A {
public static int y = 3;
public int x = 0;
public B (double x) {
super((int) x);
}
public void f(int y) {
this.x = y*2;
B.y = this.x;
}
public void f(double y) {
this.x = (int) y + B.y;
}
}
public class M {
public static void main (String[] args){
A a = new A(B.y);
a.f(1);
B b = new B(3.0);
A z = b;
z.f(-5.0);
z.f(-6);
System.out.println(b.x + " " + z.x);
}
}
我覺得Mike Samuel的回答很好,因爲z有類型A,儘管它擁有A的一個子類B的實例,但只有A的方法可以被調用;對於子類型B的方法的調用,你將不得不downcast z(儘管使用checked downcast,例如使用instanceof,因爲否則可能會遇到運行時異常)。 - 在一個不相干的筆記上,既然我看到了你對理論計算機科學的簡介,並且正在考慮在RWTH做我的主人,那麼在那裏學習怎麼樣?從您對TCS的問題來看,聽起來有些苛刻? – 2012-03-13 23:51:48
編輯:我誤讀了麥克塞繆爾的答案,在他的第一句話,它需要閱讀「A.f(雙)」。一個正確的,不太詳細的答案(這也是不太需要,而仍然捕捉問題)將是悲慘變量的;也檢查那一條的評論。 – 2012-03-14 00:33:56
@ G. Bach:我可以強烈推薦RWTH大學。這很有挑戰性,但很有趣。我只是在我的第一個學期,所以我的經驗是相當有限的;-) – Laura 2012-03-15 18:46:09