如何在java中访问另一个类的构造函数?

时间:2017-03-08 11:03:56

标签: java inheritance constructor overloading

我有一个名为" Question"的超类。我有两个派生自它的子类,名为" QuestionSA" (简答)和#34; QuestionTF" (真/假)。

这就是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做到这一点?

2 个答案:

答案 0 :(得分:3)

如果@ViewChild('layout') canvasRef; //other code here drawRectangle(file: any): void { let canvas = this.canvasRef.nativeElement; let context = canvas.getContext('2d'); let source = new Image(); source.onload = () => { context.drawImage(source, 0, 0); context.beginPath(); context.rect(file.left, file.top, file.width, file.height); context.stroke(); }; source.src = this.imgUrl; } QuestionTF的子类,您可以使用QuestionSA关键字访问其构造函数。

super

如果没有,则不能使用父类构造函数的子类来创建新对象。

答案 1 :(得分:3)

JVM在创建类的对象期间调用构造函数。因此,如果要调用类的构造函数,则需要创建该类的对象。 如果要从子类调用父类的构造函数,则可以在子构造函数的第一行中调用super()。