Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

java - 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
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...