본문 바로가기

Language/JavaScript

Cannot make a static reference to the non-static field 오류

머리말

  자바로 프로그래밍을 시작하면, 종종 'non-static field' 오류와 직면하는 경우가 발생한다. 본 포스팅에서는 해당 에러 메시지에 대해서 설명하고, 오류 상황을 해결하는 방법에 대해서 설명한다. 오래전에 작성된 포스팅인데, 티스토리 플랫폼이 리뉴얼됨에 따라 본 포스팅도 새롭게 리뉴얼해서 작성했다.

 

 

 

Cannot make a static reference to the non-static field error

  자바는 객체지향 언어로써 보다 완벽한 객체지향 프로그래밍을 위해 탄생한 언어이다. 자바 코드를 컴파일 함으로써 클래스 파일을 생성하고, 컴파일된 클래스 파일을 실행함으로써 자바 코드는 실행된다. 여기서, 컴파일되는 순서가 객체의 멤버에 따라 다르기 때문에 해당 오류가 발생한다. 아래의 예제 코드와 같이 main 메서드에서 msgWelcome 메서드를 호출하거나 i 필드를 참조하면 해당 오류 메시지가 발생한다.

 

 



1
2
3
4
5
6
7
8
9
10
11
12



public class Wookoa{
    int i = 10;


    void msgWelcome(){
        System.out.println("Wookoa!");
    }
    
    public static void main(String[] args){
       msgWelcome();
        i = 20;
    }
}


Colored by Color Scripter

 

 

# Error Message

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 

 Cannot make a static reference to the non-static method msgWelcome() from the type Wookoa

 Cannot make a static reference to the non-static field i

 

  main 메서드에서는 static으로 선언되지 않은 i 필드와 msgWelcome 메서드를 참조하고 있으며, 오류 메시지의 내용은 static으로 선언되지 않은 메서드나 필드를 참조할 수 없다는 오류 메시지다.

  참조할 수 없는 이유는 컴파일 순서에서 찾을 수 있다. 다른 멤버보다 static 멤버가 먼저 컴파일되기 때문에, static 멤버의 컴파일 시점에서는 static이 아닌 메서드나 필드는 정의되지 않았기 때문이다. 따라서, 모든 메서드나 필드를 static 멤버로 바꾸거나 Wookoa 클래스의 객체를 직접 생성해서 접근하는 방법으로 우회해야 한다.

 

 

 

# static 멤버로 전환하는 방법

 



1
2
3
4
5
6
7
8
9
10
11
12



public class Wookoa{
    static int i = 10;


    static void msgWellcome(){
        System.out.println("Wookoa!");
    }
    
    public static void main(String[] args){
        msgWellcome();
        i = 20;
    }
}


Colored by Color Scripter

 

 

# 클래스 객체를 생성해서 접근하는 방법

 



1
2
3
4
5
6
7
8
9
10
11
12
13
14



public class Wookoa{
    int i = 10;


    void msgWellcome(){
        System.out.println("Wookoa!");
    }
    
    public static void main(String[] args){
        Wookoa wookoa = new Wookoa();


        wookoa.msgWellcome();
        wookoa.i = 20;
    }
}


Colored by Color Scripter

 

 

 

 

꼬리말

  본 포스팅에서 설명한 해결방법을 다시 생각해보면, 클래스의 컴파일 순서를 한번 더 이해할 수 있다. 두 가지 방법 모두 컴파일 시점을 앞당기는 방법이다. static 멤버로 전환해서 해결하는 방법은 참조되는 객체 자체의 컴파일 시점을 변경함으로써 시점을 앞당기는 반면에, 참조하려는 클래스 객체를 생성해서 접근하는 방법은 main 메서드에서 객체를 생성했기 때문에 컴파일러가 컴파일을 추가로 요청함으로써 컴파일 시점을 앞당기는 방법이다. 최초로 컴파일이 수행되는 static 멤버 목록에 포함되냐 포함되지 않냐의 차이가 있다.



출처: https://wookoa.tistory.com/80 [Wookoa]