简体   繁体   中英

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.

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!!

TrueFalse should probably be static , as it's not associated with an outer instance of TypesOfQuestions ; it is a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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