2 回答

TA貢獻1831條經驗 獲得超9個贊
您可以使用super而不是調用重寫的方法this。
class Example extends Parent {
@Override
void method() {
super.method(); // calls the overridden method
}
}
如果你想強制每個子類調用父類的方法,Java 并沒有為此提供直接的機制。但是您可以使用調用抽象函數的最終函數來允許類似的行為(模板方法)。
abstract class Parent {
final void template() { // the template method
System.out.println("My name is " + this.nameHook());
}
protected abstract String nameHook(); // the template "parameter"
}
class Child {
@Override
protected String nameHook() {
return "Child"
}
}
然后你可以通過調用模板方法來運行程序,該方法僅由父類定義,并且它會調用子類的鉤子方法,子類都必須實現這些方法。

TA貢獻1807條經驗 獲得超9個贊
如果你有類似的東西:
abstract class Room{
abstract void render(Canvas c){
//impl goes here
}
}
然后在你的子類中你可以這樣做:
class SpecificRoom extends Room{
void render(Canvas c){
super.render(c);//calls the code in Room.render
}
}
添加回答
舉報