2017-03-08 138 views
-2

我有一個叫做「問題」的超類。我有兩個從它派生的子類,稱爲「QuestionSA」(簡答)和「QuestionTF」(真/假)。如何在java中訪問另一個類的構造函數?

這是QuestionSA樣子:

public class QuestionSA extends Question { 

private static char[] givenAnswer; 

// ======================================================== 
// Name: constructor 
// Input: the type of question, the level, 
// the question and answer, as strings 
// Output: none 
// Description: overloaded constructor that feeds data 
// ======================================================== 
QuestionSA(String type, String level, String question, String answer) { 
    this.type = type; 
    this.level = level; 
    this.text = question; 
    this.answer = answer; 
} 

我需要從QuestionTF訪問構造函數QuestionSA。我已經在C++中這樣做了:

QuestionTF::QuestionTF(string type, string level, string question, string answer) 
: QuestionSA(type, level, question, answer) {} 

如何在Java中執行此操作?

+0

你也可以添加QuestionTF類嗎? – Jens

+0

我必須編輯澄清。我知道這個命名錶明這是兒童班,但我必須檢查它的兩倍。 – ByeBye

+1

爲什麼'givenAnswer'是靜態的? – tkausl

回答

3

如果QuestionTFQuestionSA的子類,則可以使用super關鍵字訪問它的構造函數。

QuestionTF(String type, String level, String question, String answer) { 
    super(type, level, question, answer); 
} 

如果不是,則不能使用父類構造函數的子類來創建新對象。

+0

據瞭解QuestionSA不是超類QuestionTF – Jens

+0

在C++中使用初始化列表表示是sublcass,不是嗎? – ByeBye

+0

並非完全一樣,QuestionSA和QuestionTF都是問題的同級派生類。 QuestionSA不是QuestionTF的超類,反之亦然。 – Dima

3

構造函數在創建類的對象期間由JVM調用。所以如果你想調用一個類的構造函數,你需要創建該類的一個對象。 如果你想從子類調用父類的構造函數,你可以在子構造函數的第一行調用super()。

+0

那麼你的意思是說,如果我在QuestionTF類中創建了QuestionSA類的實例,那麼無論我傳遞給QuestionTF的構造函數的參數都將傳遞給QuestionSA的構造函數?這是我在C++中完成這個工作的全部原因。 – Dima

相關問題