학습 목표
1. static 변수에 대한 개념을 이해하자.
static 변수는 프로그래밍에서 중요한 개념 중 하나입니다. 클래스 변수라고도 불리며, 클래스의 모든 인스턴스가 공유
할 수 있는 변수입니다. 즉, 객체가 동일한 static 변수의 값을 공유합니다.
왜 클래스 변수라고 불리는 걸까?
우리가 자바 프로그램을 실행을 하면 프로그램을 수행하기 위해 운영체제로부터 할당받는 메모리들이 존재 합니다. 그 특성에 따라 영역등이 존재 하는데 그 구성요소들은 아래와 같습니다.
메모리 영역(JVM Memory, Runtime Data Area)

package basic.ch12;
public class NumberPrintTest2 {
public static void main(String[] args) {
// 객체 각각에 존재하는 멤버 변수를 사용하려면
// 메모리에 올라가야 사용을 할 수 있다.
// NumberPrinter n1 = new NumberPrinter(1);
// static 변수를 클래스 변수라고 불린다.
// static 변수는 클래스 이름. 으로 접근할 수 있다.
System.out.println(NumberPrinter.waitNumber);
} // end of main
}
공통으로 사용하는 변수가 필요한 경우
● 여러 인스턴스가 공유하는 기준 값이 필요한 경우
● 학생마다 새로운 학번 생성
● 카드회사에서 카드를 새로 발급할때마다 새로운 카드 번호를 부여
● 회사에 사원이 입사할때 마다 새로운 사번이 필요한 경우
● 은행에서 대기표를 뽑을 경우(2대 이상)
package basic.ch12;
// 번호를 뽑아 주는 기계
public class NumberPrinter {
// 멤버 변수
private int id;
// static 을 사용
// static 을 사용하면 Method Area 로 이동한다.
// 속도는 Method Area 가 Heap 보다 빠르다.
// private int waitNumber; // 멤버 변수
// static 변수 --> Method Area
// waitNumber 먼저 올라감
public static int waitNumber; // Method Area
public NumberPrinter(int id) {
this.id = id;
waitNumber = 1;
} // 생성자
// 기능 -- 번호표를 출력 한다.
public void printWaitNumber() {
System.out.println(id +" 번에 기기의 대기 순번은 " + waitNumber);
waitNumber++;
} // 메서드
}
package basic.ch12;
public class NumberPrintTest {
public static void main(String[] args) {
NumberPrinter n1 = new NumberPrinter(1); // 왼쪽 기기
NumberPrinter n2 = new NumberPrinter(2); // 오른쪽 기기
n1.printWaitNumber(); // 고객 1
n1.printWaitNumber(); // 고객 2
n1.printWaitNumber(); // 고객 3
n1.printWaitNumber(); // 고객 4
n2.printWaitNumber(); // 고객 5
n2.printWaitNumber(); // 고객 6
} // end of main
}
package basic.ch12;
public class NumberPrintTest2 {
public static void main(String[] args) {
// 객체 각각에 존재하는 멤버 변수를 사용하려면
// 메모리에 올라가야 사용을 할 수 있다.
// NumberPrinter n1 = new NumberPrinter(1);
// static 변수를 클래스 변수라고 불린다.
// static 변수는 클래스 이름. 으로 접근할 수 있다.
System.out.println(NumberPrinter.waitNumber);
} // end of main
}
static --->
런 ---> 실행버튼 ---> 메모리 영역
1. Method Area 영역 (Static)영역
2. Stack 영역 <-- 메인함수 찾아가는 것
3. Heap 영역 <-- 객체들이 많이 존재
'Java' 카테고리의 다른 글
| 2024.04.19 static 메소드(함수) (0) | 2024.04.19 |
|---|---|
| 2024.04.19 static 으로 숫자를 중복사용 하지 않는 방법 (0) | 2024.04.19 |
| 2024.04.18 ver 0.0.1 Starcraft (0) | 2024.04.18 |
| 2024.04.18 this 3가지 사용 방법 (0) | 2024.04.18 |
| 2024.04.17 접근 제어 지시자 (0) | 2024.04.17 |