프로그램상에서 사용되는 변수들은 사용 가능한 범위를 가진다. 그 범위를 변수의 스코프라고 한다.
// 변수가 선언된 블럭이 그 변수의 사용 범위이다.
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);
}
}
globalScope
의 사용범위는 클래스 전체 이다.int value
는 블럭 바깥에 존재하기는 하지만,메서드 선언부에 존재하므로 사용범위는 해당 메소드 블럭 내이다.localScope
변수의 사용범위는 메서드 블럭내이다.globalScope
변수를 사용할 수 없다.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; // -> static화
public void scopeTest(int value){
int localScope = 20;
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
static한 변수는 공유 된다.
- static하게 선언된 변수는 값을 저장할 수 있는 공간이 하나만 생성된다. 그러므로, 인스턴스가 여러개 생성되도 static한 변수는 하나다.
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7; // -> static화
//----위 같은 조건 이라면----//
VariableScopeExam v1 = new VariableScopeExam();
VariableScopeExam v2 = new VariableScopeExam();
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 이 출력된다.
// static이 들어간 클래스 변수는 위 코드 처럼 레퍼런스.변수명 보다
// 클래스명.변수명이 더 바람직하다 (아래 코드 참조)
System.out.println(VariableScopeExam.staticVal);
glboalScope
같은 변수(필드)는 인스턴스가 생성될 때 생성되기 때문에 인스턴스 변수라고 한다.staticVal
같은 static한 필드를 클래스 변수라고 한다.VariableScopeExam.staticVal
간단히 말해 개별 인스턴스에 포함되면 인스턴스 메서드
클래스 전체에 대한 처리 or 클래스의 개별 인스턴스와 관계없는 처리를 할 때 사용
참조 사이트
https://school.programmers.co.kr/learn/courses/5/lessons/231#