如何在java中访问另一个类的构造函数?
问题描述:
我有一个叫做“问题”的超类。我有两个从它派生的子类,称为“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中执行此操作?
答
如果QuestionTF
是QuestionSA
的子类,则可以使用super
关键字访问它的构造函数。
QuestionTF(String type, String level, String question, String answer) {
super(type, level, question, answer);
}
如果不是,则不能使用父类构造函数的子类来创建新对象。
答
构造函数在创建类的对象期间由JVM调用。所以如果你想调用一个类的构造函数,你需要创建该类的一个对象。 如果你想从子类调用父类的构造函数,你可以在子构造函数的第一行调用super()。
+0
那么你的意思是说,如果我在QuestionTF类中创建了QuestionSA类的实例,那么无论我传递给QuestionTF的构造函数的参数都将传递给QuestionSA的构造函数?这是我在C++中完成这个工作的全部原因。 – Dima
你也可以添加QuestionTF类吗? – Jens
我必须编辑澄清。我知道这个命名表明这是儿童班,但我必须检查它的两倍。 – ByeBye
为什么'givenAnswer'是静态的? – tkausl