2017-03-08 139 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

相关问题