【发布时间】:2020-04-07 21:02:16
【问题描述】:
我有一个超类,我将其实例化为 ArrayList。超类的子类保存在 ArrayList 中。现在我想从 ArrayList 中获取信息,但是属性的 getter 只在子类中可用。我可以从在抽象超类中具有抽象声明的其他类中获取信息(也保存在 ArrayList 中)。但是,我不喜欢在所有扩展超类的类中实现“虚拟”方法。
代码被截断:
public class Question{
QuestionPool() {
questionPool = new ArrayList<Question>();
ClozeQuestions q15 = new ClozeQuestions("Erster Text", "Zweiter Text");
questionPool.add(q15);
}
public int startQuiz{
System.out.printf("Q: %s", questionPool.get(i).?????
}
}
public abstract class Question {
String question;
public String getQuestion() {
return question;
}
}
public class ClozeQuestions extends Question {
ClozeQuestions(String questionPart1, String questionPart2){
this.questionPart1 = questionPart1;
this.questionPart2 = questionPart2;
}
public String getQuestionPart1() {
return questionPart1;
}
public String getQuestionPart2() {
return questionPart2;
}
}
为了规避这个问题,我在 Question 类中实现了一个“辅助方法”:
ClozeQuestions question2ClozeQuestion = new ClozeQuestions();
return question2ClozeQuestion.getQuestionPart1();
}
我从 QuestionPool 类中调用:
System.out.printf("Q: %s", questionPool.get(i).getQuestionPart1());
【问题讨论】:
-
嗯,您的代码中有多个编译错误。您的助手也没有任何意义,它是从
ClozeQuestions的新实例中提取的,其中没有任何值。为什么您将列表输入为List<Question>而不是List<ClozeQuestions>? -
如果只添加这种类型,为什么
questionPool是ArrayList<Question>而不是ArrayList<ClozeQuestions>。如果还有其他问题类型,getQuestionPart1对这些问题的期望结果是什么? -
ArrayList
还必须保存其他类型。其他问题类型有其他结构。