我有一個超類,有2個子類。如果條件foo是真正我想要的子類的一個採取一些行動,而其他子類都應該什麼都不做:有沒有解決方法在子類中清空方法?
public void doFoo() {
// some 10 lines common to both subclasses.
boolean foo = checkFoo();
/**
* if foo is true, subclass1 should do something. subcass2 does nothing.
*/
// some 10 lines common to both subclasses.
}
我想出瞭解決辦法:
public void doFoo() {
// some 10 lines common to both subclasses.
boolean foo = checkFoo();
if (foo) {
doSomething();
}
// some 10 lines common to both subclasses.
}
class subclass1 extends superclass {
public void doSomething() {
// some lines of code.
}
}
class subclass2 extends superclass {
public void doSomething() {
// do nothing
}
}
對這個常見問題有什麼更清潔,更好,更標準的解決方案?
您是否需要派生類中的顯式空函數?您可以只在基礎中具有空函數,並且只在需要它的子類中覆蓋它 – UnholySheep