简体   繁体   English

Java内部类和HashMaps

[英]Java Inner Classes and HashMaps

So I am working on a Java project, and one of my classes uses inner nested classes (the TypesOfQuestions) and when I try to add a question from the inner class to the HashMap, it doesn't let me, and I'm not sure why. 所以我正在开发一个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);
    }
}    

And the other class is Exam, which 另一堂课是考试,其中

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));

}
}

I've tried a bunch of different things, but I keep getting errors, for this one I got 我尝试过很多不同的东西,但是我一直都会遇到错误

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 I have no idea what to do!! Anndddd我不知道该怎么办!!

TrueFalse should probably be static , as it's not associated with an outer instance of TypesOfQuestions ; TrueFalse应该是static ,因为它与TypesOfQuestions的外部实例TypesOfQuestions ; it is a TypesOfQuestions . 一个TypesOfQuestions

Change your nested class to be static, so that it doesn't require an implicit reference to the outer class. 将嵌套类更改为静态类,以便它不需要对外部类的隐式引用。

    public static class TrueFalse extends TypesOfQuestions { ... }

Inner classes without the static qualifier are allowed to access the members of the outer class. 允许不带静态限定符的内部类访问外部类的成员。 This requires that they hold an implicit reference to the outer class. 这要求它们持有对外部类的隐式引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM