2017-03-08 3 views
-2

"Question"라는 수퍼 클래스가 있습니다. 나는 "QuestionSA"(짧은 대답)와 "QuestionTF"(참/거짓)이라는 두 개의 하위 클래스를 파생시킵니다.java에서 다른 클래스의 생성자에 액세스하는 방법은 무엇입니까?

이 같은 QuestionSA는 모습입니다 : 내가 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; 
} 

. 나는 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

QuestionSA의 경우 QuestionTF이 하위 클래스 인 경우 super 키워드를 사용하여 생성자에 액세스 할 수 있습니다.

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

그렇지 않으면 새 개체 생성에 부모 클래스 생성자의 하위 클래스를 사용할 수 없습니다.

+0

QuestionSA는 QuestionTF의 수퍼 클래스가 아닙니다. – Jens

+0

C++에서 초기화 목록을 사용하는 것이 서브 클래스임을 나타냅니다. 그렇지 않습니까? – ByeBye

+0

정확하지는 않지만 QuestionSA와 QuestionTF는 모두 동일한 레벨의 파생 된 질문 클래스입니다. QuestionSA는 QuestionTF의 수퍼 클래스가 아니며 그 반대도 마찬가지입니다. – Dima

3

생성자가 클래스의 객체를 만드는 동안 JVM에 의해 호출됩니다. 따라서 클래스의 생성자를 호출하려면 해당 클래스의 객체를 만들어야합니다. 자식 클래스에서 부모 클래스의 생성자를 호출하려는 경우 자식 생성자의 첫 번째 줄에서 super()를 호출 할 수 있습니다.

+0

QuestionTF 클래스에서 QuestionSA 클래스의 인스턴스를 만든 다음 QuestionTF의 생성자에 대해 전달한 모든 인수가 QuestionSA의 생성자로 전달된다는 것을 의미합니까? 이것이 내가 C++에서 한 모든 이유입니다. – Dima

관련 문제