为什么从 main 中读取非静态变量会出现问题? [英] Why is there a problem with a non-static variable being read from main?

查看:13
本文介绍了为什么从 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
}

错误:无法对非静态字段名称进行静态引用

ERROR: Cannot make a static reference to the non-static field name

推荐答案

导致这个问题的原因是 main 是一个静态方法,这意味着它没有接收器对象.换句话说,它不会相对于某个对象进行操作.因此,如果您尝试查找非静态字段,那么 Java 会混淆该字段所在的对象.通常,它会假设该字段位于调用方法的对象中,但是因为 main 是静态的,这个对象不存在.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆