프로그램상에서 사용되는 변수들은 사용 가능한 범위를 가진다. 그 범위를 변수의 스코프라고 한다.
변수가 선언된 블럭이 그 변수의 사용범위이다.
public class ValableScopeExam{
int globalScope = 10; // 인스턴스 변수
public void scopeTest(int value){
int localScope = 10;
System.out.println(globalScope);
System.out.println(localScpe);
System.out.println(value);
}
}
public class VariableScopeExam {
int globalScope = 10;
public void scopeTest(int value){
int localScope = 20;
System.out.println(globalScope);
System.out.println(localScope);
System.out.println(value);
}
public static void main(String[] args) {
System.out.println(globalScope); //오류
System.out.println(localScope); //오류
System.out.println(value); //오류
}
}
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7;
public void scopeTest(int value){
int localScope = 20;
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
ValableScopeExam v1 = new ValableScopeExam();
ValableScopeExam v2 = new ValableScopeExam();
v1.golbalScope = 20;
v2.golbalScope = 30;
System.out.println(v1.golbalScope); //20 이 출력된다.
System.out.println(v2.golbalScope); //30이 출력된다.
v1.staticVal = 10;
v2.staticVal = 20;
System.out.println(v1.statVal); //20 이 출력된다.
System.out.println(v2.statVal); //20 이 출력된다.