2012-03-23 88 views
0

我希望子類總是爲某些方法調用super()。 如何在編譯時執行或至少發出警告?如何在Java/eclipse中添加不調用super()的警告

感謝

+2

沒有一些例子,我們不知道你在說什麼。如果需要的話,方法會調用'super()...',這完全取決於實現細節。對此沒有一般的答案。 – 2012-03-23 01:17:44

+1

我不認爲這是可能的。但是,我也不認爲它真的是你想要的。強制調用超級方法違反了多態的原則。 – 2012-03-23 01:17:53

+0

我知道強制調用超級不好。但我沒有擁有超級課程。和SDK文檔需要調用超級。例如[鏈接](http://developer.android.com/reference/android/test/ServiceTestCase.html#setUp%28%29) – 2012-03-23 01:33:50

回答

2

我認爲Chris White的答案在一般情況下是最好的。但陳瑩的評論「我知道強制調用超級不好,但我沒有擁有超級類,並且SDK文檔需要調用super。例如鏈接」暗示它不適用於此特定實例。

因此,我會建議修改克里斯懷特的答案,以滿足詳情。

class ChenYingTestCase extends ServiceTestCase 
{ 
     /** 
     * Gets the current system context and stores it. 
     * You can not extend this method. 
     * If you want to achieve the effect of extending this method, 
     * you must override chenYingSetupMethod. 
     **/ 
     public final void setUp () 
     { 
      super.setUp () ; 
      chenYingSetup () ; 
     } 

     /** 
     * Does nothing (unless you extend it) 
     * 
     * Extend this method to do your 
     * own test initialization. If you do so, there is no need to call super.setUp() 
     * Hint: calling super.setUp() is probably a bad idea. 
     * as the first statement in your override. 
     * Just put your test initialization here. 
     * The real SetUp method will call super.setUp() and then this method. 
     **/ 
     protected void chenYingSetUp () 
     { 
     } 
} 

然後如果一個子類在你的控制下,使它成爲ChenYingTestCase的子類。如果子類不在你的控制之下,那麼你不能強迫它調用super()。

+1

的一個很好的例子換句話說,將問題移動到封裝超類的第一個直接子類,然後強制子類只實現他們需要的邏輯。好計劃。 +1 – 2012-03-23 03:16:57

8

你可以工程師這一點不同,以強制執行的行爲:

超類應該是抽象的,或者至少定義方法決賽。然後定義一個受保護的方法,該子類必須實現終於有超類調用方法完成需要事先運行任何代碼之後:

public abstract class SuperClass { 
    // final so it can't be overriden 
    public final void superMethod() { 
     // required code here 

     // then delegate to implMethod 
     implMethod(); 
    } 

    protected abstract() void implMethod(); 
} 

public class SubClasss extends SuperClass { 
    protected void implMethod() { 
     // sub class logic 
    } 
} 

當然,父類並不一定是抽象的,你可以實現implMethod,然後允許子類覆蓋它

+0

這是http://checkstyle.sourceforge.net/config_design.html#DesignForExtension – emory 2012-03-23 01:25:49

0

如果基類有一個默認(無參數)構造函數,如果沒有給出明確的super()調用,它將總是自動調用。如果你有在基類的控制,可以使默認的構造函數私有:

public abstract class Whatever { 
    private Whatever() { 
     // not visible to subclasses 
    } 

    public Whatever(A a, B b, ...) { 
     // this constructor must always be explicitly called by subclasses 
    } 
} 

除非是,你的IDE可以讓你打開這個警告。它將在選項菜單中的某處。如果你沒有看到它,它不在那裏。