Problem category: Compile-time Problems
Diagnosis Difficulty: Easy
Difficulty to Fix: Easy-medium
This problem occurs when you try to access an instance variable in a static way. The most common way this happens is to try to use an instance variable from a static method (such as the main method) without creating an instance of that object. For more information on static and instance variables/methods, see Understanding Instance and Class Members.
The second common mistake is to forget to declare your static variables as static (the default is as an instance variable)
Public class Test { public int count; public static void main(String[] args) { count = 0; while(count < 5) { ++count; } } }
This problem can also manifest itself by trying to call a non-static method.
Error Messages
The error message for this error is very common, and easily indicates what the actual problem is.
Test.java:7: non-static variable a cannot be referenced from a static context
a = 5;
a = 5;
Test.java:10: non-static method doIt() cannot be referenced from a static context
doIt();
doIt();
Depending on your situation, you will either want to change the variable/method declaration to be static, or you will want to create a new instance of the object and reference the field/method from that object.
Public class Test { public static int count; public static void main(String[] args) { count = 0; while(count < 5) { ++count; } } }