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?
Here’s your example:
The method
mainis a static method associated with the class. It is not associated with an instance ofMember, so it cannot access variables that are associated with an instance ofMember. The solution to this is not to make those fields static. Instead, you need to create an instance ofMemberusing thenewkeyword.Here’s a modified version:
Finding yourself creating global statics is an indication to you that you should think carefully about how you’re designing something. It’s not always wrong, but it should tell you to think about what you’re doing.