티스토리 뷰

매우 간단하며, 누구나 알법한 내용이다.

static 메소드에서 static이 아닌 메소드를 참조할 수 없다.


코드로 한 번 보자.

1
2
3
4
5
6
7
public class RenoV{
    String hello = "Hello, RenoV!";
 
    public static void main(String args[]){
        System.out.println(hello);
    }
}
cs

위 코드를 실행하면 오류가 발생한다.

static 메소드인 main 안에서 static이 아닌 String인 hello를 참조했기 때문이다.

이 코드가 올바르게 동작하려면 아래와 같이 수정해야 한다.

1
2
3
4
5
6
7
public class RenoV{
    static String hello = "Hello, RenoV!";
 
    public static void main(String args[]){
        System.out.println(hello);
    }
}
cs

이렇게 hello를 static 변수로 설정하면 정상적으로 참조가 가능하다.

'개발 이야기 > Tip & Troubleshooting' 카테고리의 다른 글

i++와 ++i  (0) 2016.02.01
공지사항