자바 공부21 - 변수의 범위(scope)
변수의 범위(Scope)
프로그램 상에서 사용되는 변수들은 사용 가능한 범위를 갖음, 그 범위를 변수의 범위(Scope)라고 함
변수가 선언된 블럭이 그 변수의 사용 범위
public class ValableScope{ int globalScope = 10; //클래스 변수 public void scopeTest(int value){ int localScope = 10; //메소드 변수
System.out.println(globalScope); System.out.println(localScpe); System.out.println(value); } }
클래스의 속성으로 선언된 변수 globalScope의 사용 범위는 클래스 전체
매게 변수로 선언된 int value 는 블럭 바깥에 존재하지만, 메서드 선언부에 존재함으로 사용 범위는 해당 메소드 내
메소드 블록내에서 선언된 localScope 변수의 사용 범위도 메소드 내
public class VariableScope { int globalScope = 10; public void scopeStudy(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); // main 메소드가 static으로 오류가 발생 됨
System.out.println(localScope); // local 변수는 scopeStudy의 지역 변수임으로 오류 발생
System.out.println(value); // value 변수는 scope의 매게 변수로 지역 변수임으로 오류 발생
}
}
같은 클래스 내에 있음에도 해당 변수들을 사용할 수 없음
main 메소드는 static이라는 키워드로 메소드가 정의되어 있음, 이런 메서드를 static한 메소드라고 함
static한 필드(필드 앞에 static 키워드를 붙임)나, static한 메소드는 Class가 인스턴스화 되지 않아도 사용할 수 있음
public class VariableScope { static int globalScope = 10; } public static void main(String[] args) { System.out.println(globalScope); // static 이 붙어서 오류가 발생되지 않음
}
Static 으로 선언된 변수는 값을 저장할 수 있는 공간이 하나만 생성됨, 그러므로 인스턴스가 여러개 생성되어도 Static 변수는 한개
참고 : tryhelloworld.co.kr