Why is there a problem with a non-static variable being read from main?

前端 未结 3 1848
粉色の甜心
粉色の甜心 2020-12-07 01:28
String name = \"Marcus\";
static String s_name = \"Peter\";

public static void main(String[] args) {    
    System.out.println(name);//ERROR
    System.out.println         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-07 02:08

    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.

提交回复
热议问题