[英]Java Inner Classes and HashMaps
所以我正在开发一个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
; 它是一个TypesOfQuestions
。
将嵌套类更改为静态类,以便它不需要对外部类的隐式引用。
public static class TrueFalse extends TypesOfQuestions { ... }
允许不带静态限定符的内部类访问外部类的成员。 这要求它们持有对外部类的隐式引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.