Måns Nilsson Måns Nilsson - 10 months ago 55
Java Question

Non-static variable this not referenceable from a static context

I'm fairly new to Java, though I've programmed in C++ before. I've made a simple class in Java:

import java.util.ArrayList;

public class ATMServer {
private static ArrayList<ArrayList<String>> savedstates = new ArrayList<ArrayList<String>>();
private static ArrayList<String> temp = new ArrayList<String>();

public static void main(String[] args) {
(this.temp).add("0123456789");
(this.temp).add("456");
(this.temp).add("200");
(this.savedstates).add((this.temp));
(this.temp).clear();
(this.temp).add("1122334455");
(this.temp).add("123");
(this.temp).add("300");
(this.savedstates).add((this.temp));
(this.temp).clear();
(this.temp).add("5566778899");
(this.temp).add("070");
(this.temp).add("175");
(this.savedstates).add((this.temp));
}
};


But when I try to compile it, I get the error "Non-static variable this cannot be referenced from a static context" for all occurrences of 'this' in the code. What causes this problem?

Answer Source

Drop the (this.temp) notation, replacing it with simply temp.

this does not mean anything in a static function since there is no implied object instance passed to the function.