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이 두번 더해진다.
'자바' 카테고리의 다른 글
자바 this로 사용하는 멤버변수 (0) | 2022.07.01 |
---|---|
자바 메소드 오버로딩 (method overloading) (0) | 2022.07.01 |
자바 new연산자를 이용한 객체 생성시 메모리와의 관계 (0) | 2022.07.01 |
자바 클래스와 객체 (0) | 2022.07.01 |
자바 배열의 길이 구하는 방법 (0) | 2022.07.01 |