class StaticVar {
	static int a = 1;
	int b = 1;
	
	public void staticTest() {
		a = a + 1;
		b = b + 1;
		System.out.println("static int a : " + a);
		System.out.println("member int b : " + b);
	}
}


public class StaticMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StaticVar v1 = new StaticVar();
		v1.staticTest();
		
		StaticVar v2 = new StaticVar();
		v2.staticTest();
	}

}

Static 변수는 Static메모리 영역에 프로그램 종료까지 남아있다.

전역변수가 프로그램이 종료될 때까지 어디서든 사용이 가능하다

위 프로그램을 돌려본 결과는 다음과 같다.

static int a : 2
member int b : 2
static int a : 3
member int b : 2

static 변수는 모든 객체가 메모리를 공유해서 1이 두번 더해진다.

 

+ Recent posts