所以我正在开发一个 Java 项目,我的一个类使用内部嵌套类(TypesOfQuestions),当我尝试将内部类中的问题添加到 HashMap 时,它不允许我,我不知道为什么。
public abstract class TypesOfQuestions {
Map<String, Double> scores = new TreeMap<String, Double>();
String text;
double points;
public TypesOfQuestions(String text, double points) {
}
public static class TrueFalse extends TypesOfQuestions {
public TrueFalse(String text, double points, boolean answer) {
super(text, points);
}
}
另一个类是考试,
public class Exam {
private String x;
private Map<Integer, Questions> q;
public HoldExam(String x) {
q = new HashMap<Integer, Questions>();
this.x = x;
}
public void addTrueFalseQuestion(int questionNumber, String text,
double points, boolean answer){
q.put(questionNumber, new TrueFalse (text, points, answer));
}
}
我已经尝试了很多不同的东西,但我总是收到错误,因为我得到了这个
No enclosing instance of type TypesOfQuestions is accessible.
Must qualify the allocation with an enclosing instance of type TypesOfQuestions
(e.g. x.new A() where x is an instance of TypesOfQuestions).
Anndddd 我不知道该怎么做!!
最佳答案
TrueFalse
应该是 static
,因为它与 TypesOfQuestions
的外部实例无关;它是一个TypesOfQuestions
。
关于Java 内部类和 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112352/