Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

햄발

static 변수 본문

Java

static 변수

햄발자 2024. 4. 19. 09:03

 

static 변수

프로그래밍에서 중요한 개념 중 하나입니다. 클래스 변수라고도 불리며, 클래스의 모든 인스턴스가 공유하는 할 수 있는 변수 이다. 즉, 객체가 동일한 static 변수의 값을 공유합니다.

 

 

클래스 변수라고 불리는 이유?

자바 프로그램을 실행을 하면 프로그램을 수행하기 위해 운영체제로부터 할당받는 메모리들이 존재 한다. 그 특성에 따라 영역등이 존재 하는데 그 구성요소들은 아래와 같다.

 

 

메모리 영역(JVM Memory, Runtime Data Area)

 

 

 

 

공통으로 사용하는 변수가 필요한 경우

  • 여러 인스턴스가 공유하는 기준 값이 필요한 경우
  • 학생마다 새로운 학번 생성
  • 카드회사에서 카드를 새로 발급할때마다 새로운 카드 번호를 부여
  • 회사에 사원이 입사할때 마다 새로운 사번이 필요한 경우
  • 은행에서 대기표를 뽑을 경우(2대 이상)

 

 

 

package basic.ch12;

// 번호 뽑아 주는 기계
public class NumberPrinter {

private int id;
// private int waitNumber; --> 멤버 변수 
// static 변수는 Method Area 영역에 올라 간다. 
// 즉 static waitNumber 변수는 NumberPrinter 인스턴스화 되기전에 사용 가능 하다. 
public static int waitNumber;     

public NumberPrinter(int id) {
this.id = id;
waitNumber = 1;
}

// 기능 -- 번호표를 출력 한다 
public void printWaitNumber() {
System.out.println( id +  " 번에 기기의 대기 순번은 " + waitNumber);
waitNumber++;
}


}

 

package basic.ch12;

public class NumberPrinterTest {

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 NumberPrinterTest2 {

public static void main(String[] args) {

// 객체 각각에 존재하는 멤버 변수를 사용하려면 메모리에 올라가야 사용을 할 수 있다. 
// NumberPrinter numberPrinter1 = new NumberPrinter(1);
// static 변수를 클래스 변수라고도 불린다. 
// static 변수는 클래스 이름. 으로 접근할 수 있다. 
System.out.println(NumberPrinter.waitNumber);

} // end of main 
}

 

 

정리

실행 버튼(프로그램 실행) ---> OS부터 메모리 영역을 할당 받는다.

 

순서

  1. Method Area(Static)
  2. Statck(main)
  3. Heap(객체)

'Java' 카테고리의 다른 글

배열  (0) 2024.04.22
static 메소드 (함수)  (0) 2024.04.19
this  (0) 2024.04.19
접근 제어 지시자  (0) 2024.04.17
생성자 (constructor)  (0) 2024.04.16