簡體   English   中英

為什么不能在子類構造函數中添加額外的參數驗證?

[英]Why can't I add extra argument validation in the subclass constructor?

我有兩節課。 超類:

public abstract class Question(){

public Question(String question, String answer, String... alts){...
}

和子類:

public class StringOptionsQuestion extends Question {

public StringOptionsQuestion(String question, String answer, String... alts){
    if (alts.length == 0){throw new IllegalArgumentException();} //The compiler doesn't like this line.
    super(question, answer, alts);
}}

我希望我的子類StringOptionsQuestion在將alts的長度傳遞給超類的構造函數之前對其進行驗證。 但是,我不能這樣做。 我收到錯誤消息“構造函數調用必須是構造函數中的第一條語句”。 為什么會出現此錯誤? 我該如何繞過它呢?

如kocko所述, super語句必須是構造函數中的第一條語句 但是,如果您確實真的不想在驗證之前深入到超構造函數(例如,因為它會因無濟於事的錯誤而崩潰),則可以在評估超構造函數的參數時進行驗證:

public class StringOptionsQuestion extends Question {

    public StringOptionsQuestion(String question, String answer, String... alts) {
        super(question, answer, validateAlternatives(alts));
    }

    private static String[] validateAlternatives(String[] alternatives) {
        if (alternatives.length == 0) { 
           throw new IllegalArgumentException();
        }
        return alternatives;
    }
}

super()語句必須是構造函數中的第一個:

super(question, answer, alts);
if (alts.length == 0) { 
    throw new IllegalArgumentException();
}

正如其他人所說,對super(...)的調用必須是子類構造函數中的第一條語句。

但是,它不必是要求值的第一個表達式

如果在調用超類構造函數之前確實需要做一些事情(這不是標准代碼,則應該記錄為什么這樣做),然后可以通過調用靜態方法作為表達式來做類似的事情:

public class StringOptionsQuestion extends Question {

    private static String[] checkAlts(String[] alts) {
        if (alts.length == 0) {
            throw new IllegalArgumentException();
        }
        return alts;
    }

    public StringOptionsQuestion(String question, String answer, String... alts) {
        super(question, answer, checkAlts(alts));
    }
}

超級類構造函數將始終被調用。 您可以顯式調用它,也可以由Java為您執行。 而且,當您從子類構造函數中顯式執行此操作時,它必須是構造函數中的第一件事。

我不確定您的要求到底是什么,但是我想是如果alts.length == 0,則要避免在StringOptionsQuestion子類的情況下構造對象。您可以通過在超級類中添加另一個構造函數來實現此目的,一個額外的布爾參數,例如'checkLength',如果其值為true,則對長度進行驗證,並在需要時拋出異常。 然后從您的StringOptionsQuestion子類中調用新的構造函數。

公共抽象類Question(){

公共問題(字符串問題,字符串答案,字符串...替代項){...}

公共問題(字符串問題,字符串答案,字符串...替代項,布爾值checkLength){

if(checkLength && alts.length == 0){引發新的IllegalArgumentException();}

}

}

公共類StringOptionsQuestion擴展了問題{

公共StringOptionsQuestion(字符串問題,字符串答案,字符串...替代項){

super(question, answer, alts, true);

}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM