static 메소드 안에서의 인스턴스 변수 사용
public class VariableScopeExam{
int globalScope = 10;
public static void main(String[] args){
System.out.println(globalScope); // 오류발생!
}
}
static 메소드 안에서의 올바른 인스턴스 변수 사용 방법
public class VariableScopeExam{
int globalScope = 10;
static int staticVal = 7; // static한 필드
public static void main(String[] args){
System.out.println(staticVal); // globalScope와 다르게 사용가능
}
}
VariableScopeExam v1 = new VariableScopeExam();
VariableScopeExam v2 = new VariableScopeExam();
v1.globalScope = 20;
v2.globalScope = 30;
System.out.println(v1.globalScope); // 결과: 20
System.out.println(v2.globalScope); // 결과: 30
v1.staticVal = 10;
v2.staticVal = 20;
System.out.println(v1.staticVal); // 결과: 20
System.out.println(v2.staticVal); // 결과: 20
VariableScopeExam.staticVal // 클래스명.변수명