8
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

Sam
  • 83
  • 4
  • Same issue as with non-static methods. See http://stackoverflow.com/questions/2042813/calling-non-static-method-in-static-method-in-java – dkarp Jan 12 '11 at 03:41

3 Answers3

6

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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Technically, the object that you're operating on is the class itself. I also wouldn't say it's a general rule...I'd say it's a rule. – Chris Thompson Jan 12 '11 at 03:48
  • I also wouldn't say Java 'gets confused'. There is nothing for it to be confused about. There is no instance object. Period. So there is no way to access an instance field. – user207421 Jan 12 '11 at 06:25
2

To access non-static member variables and functions, you must have a specific object. (e.g. if all that was inside class Bob { ... }, you would need to do something like

Bob bob = new Bob(); 
System.out.println(bob.name);

inside your main.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Matt
  • 678
  • 1
  • 6
  • 13
0

name is an instance variable in this case, and you are trying to access it without an object created, so technically name variable doesn't exist in memory, but for a static variable(s_name), its a class variable, it comes into existence once the class is created.