![](/img/trans.png)
[英]Why can we not override private members of a super class in a sub class?
[英]How do we call a super class method if we already have a super class of sub class?
我的問題是,如果有一個由父類擴展的子類,又由祖父類擴展的子類,那么子類如何直接訪問祖父的方法。
最好用一個例子說明:
public class GF {
public void one() { ... }
public void two() { ... }
}
public class F extends GF {
public void two() { ... }
}
public class C extends F {
public void one() {
super.one(); // Calls one in GF
}
public void two() {
super.two(); // Calls two in F
}
}
從子類內部調用重寫的方法的語法是super.method(....)
。 但是您只能執行此操作以調用第一級重寫方法。 如果該方法本身是替代,則不能調用第二級替代;否則,您不能調用第二級替代。 例如C.two()
無法直接調用GF.two()
。 您不能進行反思,甚至JVM字節碼也不允許這樣做。
這取決於祖父的方法可見性。 通常,可以像父親的方法一樣訪問它。 如果要跳過父級對祖父方法的替代,則不能不修改父級就執行此操作。
調用祖父方法的唯一方法是這樣的:
public class GF {
public void m() {
//do something
}
}
public class F {
public void m() {
//do something that you don't need in son
}
/* add this method for the clean access to GF*/
public void gfM() {
super.m();
}
}
public class S {
public void aMethod() {
gfM(); //actually calls the GF.m() method
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.