1

所以我正在研究一个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).

安德德我不知道该怎么办!

4

2 回答 2

3

TrueFalse可能应该是static,因为它与 ; 的外部实例无关TypesOfQuestions。它一个TypesOfQuestions.

于 2013-04-19T19:43:04.720 回答
1

将您的嵌套类更改为静态,以便它不需要对外部类的隐式引用。

    public static class TrueFalse extends TypesOfQuestions { ... }

允许没有static 限定符的内部类访问外部类的成员。这要求它们持有对外部类的隐式引用。

于 2013-04-19T19:43:24.100 回答