我已经多次遇到这个问题,但我从来没有费心去了解它为什么会发生,也没有去了解“静态”的真正含义。我只是应用了 Eclipse 建议的更改并继续。
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
}
所以 eclipse 告诉我做 static int iNumVertices;
我不确定为什么。那么究竟什么是“静态”,它是如何使用的,使用“静态”的目的是什么,为什么会给我这个问题?
最佳答案
这是你的例子:
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
}
}
main
方法是与类关联的静态方法。它不与 Member
的实例相关联,因此它无法访问与 Member
的实例相关联的变量。对此的解决方案是不使这些字段成为静态的。相反,您需要使用 new
关键字创建 Member
的实例。
修改后的版本:
public class Member {
// Fields
private int iNumVertices;
private int iNumEdges;
public Member(){
// init the class
}
public static void main(String[] args) {
Member member = new Member();
member.iNumVertices = 0;
// do more stuff
}
}
发现自己在创建全局静态,这表明您应该仔细考虑如何设计某些东西。这并非总是是错误的,但它应该告诉您考虑您正在做的事情。
关于java - 在 Java 中声明 "static"变量时 "global"到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3415781/