I've been running into this problem many times and I never bothered to learn why its happening and learn what "static" actually means. I just applied the change that Eclipse suggested and moved on.
public class Member {
// Global Variables
int iNumVertices;
int iNumEdges;
public static void main(String[] args) {
// do stuff
iNumVertices = 0; // Cannot make a static reference to the non-static field iNumVertices
// do more stuff
} // main end
}
So eclipse tells me to do static int iNumVertices;
and I'm not sure why. So what exactly is "static", how is it used, what is the purpose of using "static", and why is it giving me this problem?
What static actually means that Class variable will be same for all instance of that particular class, however if you want to avoid using static variables(which is a good idea, since static variables are being kept in memory) you can pass variable value trough constructor thereby avoiding usage of static modifier, and achieve the same effect(that is if you pass the same value upon class instantiation).
Here is code example :
So you can do this when creating new instance :
and every time you create Car instance it will have speed 100, thus avoiding static declaration
private static int speed = 100;
Static variables do not need to have the class be instantiated in order to be accessed, so if you are trying to access a non-static variable form a static context you are risking trying to access something that has not been initialized/instantiated.