1. 에러 원인: "Non-static variable cannot be referenced from a static context"
Java에서 non-static
변수는 클래스의 인스턴스와 관련이 있습니다. 반면, static
메서드는 클래스 자체와 관련되므로, 특정 인스턴스에 속한 변수를 직접 참조할 수 없습니다. 아래 코드를 예로 들어보겠습니다.
class MyProgram {
int count = 0;
public static void main(String[] args) {
System.out.println(count); // 에러 발생
}
}
위 코드에서는 count
가 non-static
변수이기 때문에 static
메서드인 main
에서 직접 참조할 수 없어 에러가 발생합니다.
2. 해결 방법
2.1 인스턴스를 생성하여 변수에 접근하기
non-static
변수는 클래스의 인스턴스를 통해 접근해야 합니다.
class MyProgram {
int count = 0;
public static void main(String[] args) {
MyProgram program = new MyProgram();
System.out.println(program.count); // 정상 출력
}
}
2.2 변수를 static으로 선언하기
static
변수는 클래스 레벨에서 공유되므로, static
메서드에서 직접 접근할 수 있습니다.
class MyProgram {
static int count = 0;
public static void main(String[] args) {
System.out.println(count); // 정상 출력
}
}
2.3 메서드를 non-static으로 선언하기
main
메서드를 제외한 다른 메서드가 static
일 필요가 없는 경우, 메서드를 non-static
으로 선언하여 non-static
변수에 접근할 수 있습니다.
class MyProgram {
int count = 0;
public static void main(String[] args) {
MyProgram program = new MyProgram();
program.printCount();
}
public void printCount() {
System.out.println(count); // 정상 출력
}
}
3. static과 non-static의 차이점
static
변수/메서드: 클래스 로드 시 메모리에 올라가며 모든 인스턴스에서 공유됩니다.non-static
변수/메서드: 클래스의 인스턴스 생성 시 메모리에 할당되며 각 인스턴스마다 독립적으로 존재합니다.
4. 결론
"Non-static variable cannot be referenced from a static context"
에러는 static
메서드와 non-static
변수의 차이를 이해하면 쉽게 해결할 수 있습니다. 위에서 소개한 방법 중 상황에 맞는 방법을 선택하여 문제를 해결하세요.