블로그   태그   위치로그   이웃로그   방명록
          
 
 
05-06 19:45
 
 
     
 
  Cannot make a static reference to the non-static field count  +   [Java]   |  2013. 4. 2. 15:58


자료 구조와 JAVA

이석호 저, 정익사


프로그램 1.1

public class JavaOne {
    int count = 1;


    public static void main(String[] args) {
        System.out.println("This count is: " + count);
    }
}


??? 예제코드에는 JavaOne에 count를 선언하고 정의하라고 되어있는데 해보면 스태틱 클래스 (main)밖의 것을 참조할 수 없다고 에러가 난다.

고치려면? count를 클래스의 객체로 만들거나 static int count로 선언해야한다!!!
왜? static 멤버들이 먼저 컴파일되면서 비스태틱 멤버인 count가 정의되지 않았기 때문.(http://enjoyjava.tistory.com/7)


솔루션 1. 참조하려는 것을 전부 스태틱으로 바꾼다.


public class JavaOne {
    static int count = 1;
    public static void main(String[] args) {
        System.out.println("this count is: " + count);
    }
}



솔루션 2. 클래스로 만들어서 객체를 생성한다.


public class JavaOne {
    int count;

    public static void main(String[] args) {
        JavaOne a = new JavaOne();
        a.count = 1;
        System.out.println("this count is: " + a.count);
    }
}



 
  
 
   

데드캣's Blog is powered by Daum & tistory