在下面这段代码中会报错
- System.out.println(s1);
System.out.println(s1);
Cannot make a static reference to the non-static field s1
只要把s1的申明加上static,就不会报错了,这有点让奇怪,看报错是说不能在非静态域进行静态引用,查询了一下原因,由于该方法是静态方法,s1变量非静态变量,所以s1是依赖于对象的存在而存在的,也就是说First对象必须实例化后内存中才存在s1,那么对于静态方法main来讲,这就是矛盾的,所以才会有这个报错。
- package number;
- public class First {
- String s1 = ”nihao”;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- System.out.println(s1);
- }
- }
package number;
public class First {
String s1 = "nihao";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(s1);
}
}
在下面这段代码中会报错
- System.out.println(s1);
System.out.println(s1);
Cannot make a static reference to the non-static field s1
只要把s1的申明加上static,就不会报错了,这有点让奇怪,看报错是说不能在非静态域进行静态引用,查询了一下原因,由于该方法是静态方法,s1变量非静态变量,所以s1是依赖于对象的存在而存在的,也就是说First对象必须实例化后内存中才存在s1,那么对于静态方法main来讲,这就是矛盾的,所以才会有这个报错。
- package number;
- public class First {
- String s1 = ”nihao”;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- System.out.println(s1);
- }
- }
package number;
public class First {
String s1 = "nihao";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(s1);
}
}