JAVA中在main函数中调用变量时注意事项

在下面这段代码中会报错


  1. 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来讲,这就是矛盾的,所以才会有这个报错。



  1. package number;  
  2.   
  3. public class First {  
  4.      String s1 = ”nihao”;  
  5.     public static void main(String[] args) {  
  6.         // TODO Auto-generated method stub            
  7.         System.out.println(s1);       
  8.     }  
  9. }  
package number;

public class First {
     String s1 = "nihao";
    public static void main(String[] args) {
        // TODO Auto-generated method stub          
        System.out.println(s1);     
    }
}

在下面这段代码中会报错


  1. 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来讲,这就是矛盾的,所以才会有这个报错。



  1. package number;  
  2.   
  3. public class First {  
  4.      String s1 = ”nihao”;  
  5.     public static void main(String[] args) {  
  6.         // TODO Auto-generated method stub            
  7.         System.out.println(s1);       
  8.     }  
  9. }  
package number;

public class First {
     String s1 = "nihao";
    public static void main(String[] args) {
        // TODO Auto-generated method stub          
        System.out.println(s1);     
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34037046/article/details/77916180
今日推荐