据说非静态变量不能在静态方法中使用。但是 public static void main
可以。怎么样?
最佳答案
不,不是。
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
但是
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
或者如果你实例化A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
还有
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
会起作用,因为 a
在这里是局部变量,而不是实例变量。方法局部变量在方法执行期间始终是可访问的,无论该方法是否为 static
。
关于java - public static void main() 访问非静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522026/