为什么从main读取非静态变量有问题? [英] Why is there a problem with a non-static variable being read from main?
问题描述
String name =Marcus;
static String s_name =Peter;
public static void main(String [] args){
System.out.println(name); // ERROR
System.out.println(s_name); // OK
}
错误:无法对非静态字段名称进行静态引用
导致问题的原因是 main
是静态方法,这意味着它没有接收器对象。换句话说,它不会相对于某个对象运行。因此,如果您尝试查找非静态字段,那么Java会对该字段所在的对象感到困惑。通常,它会假定该字段位于调用该方法的对象中,但是因为 main
是静态的,该对象不存在。
作为一般规则,您无法从静态方法访问常规实例变量。 / p>
String name = "Marcus";
static String s_name = "Peter";
public static void main(String[] args) {
System.out.println(name);//ERROR
System.out.println(s_name);//OK
}
ERROR: Cannot make a static reference to the non-static field name
The reason this causes a problem is that main
is a static method, which means that it has no receiver object. In other words, it doesn't operate relative to some object. Consequently, if you try looking up a non-static field, then Java gets confused about which object that field lives in. Normally, it would assume the field is in the object from which the method is being invoked, but because main
is static this object doesn't exist.
As a general rule, you cannot access regular instance variables from static methods.
这篇关于为什么从main读取非静态变量有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!