static과 메모리
메인 클래스의 동작 원리
- JVM(Java Virtual Machine)이 실행할 클래스를 찾는다.
- static 키워드가 붙은 멤버들을 static 메모리 영역에 자동으로 한 번 로딩한다.
- static 멤버들은 클래스를 사용하는 시점에 딱 한 번만 메모리에 로딩된다.
- main() 메서드의 경우 static이므로 메모리에 로딩된다.
- JVM이 static 메모리 영역에서 main() 메서드를 호출한다.
- 호출한 메서드를 Call static Frame Area(Stack Area)에 push한 뒤 동작을 시작한다.
JVM의 Memory Model
- Method Area
- 메서드의 기계어코드가 할당되는 메모리 공간
- static-zone, none-static-zone으로 나뉨
- Heap Area
- 객체가 생성되는 메모리 공간
- Garbage Collector에 의해서 더 이상 사용되지 않는 객체들이 관리됨
- Stack Area (Call Stack Frame Area)
- 메서드 호출 시 기계어코드를 할당받아 메서드가 실행되는 메모리 공간
- Program Counter에 의해 현재 실행중인 프로그램의 위치를 관리
- LIFO 구조
- Runtime Constant Pool (Literal Pool)
- 상수 값이 할당되는 메모리 공간
- 문자열 상수가 할당되는 메모리 공간
static의 객체 생성
- static 멤버의 경우 객체 생성 없이 호출하는 것이 바람직하다.
- 객체 생성을 하지 못하도록 막는 방법
: 접근제어자를 이용하여 생성자 메서드에 접근하지 못하도록한다.
public class AllStaticTest {
public static void main(String[] args) {
int a = 3;
int b = 4;
System.out.println(AllStatic.sum(a, b));
System.out.println(AllStatic.max(a, b));
System.out.println(AllStatic.min(a, b));
}
}
public class AllStatic {
private AllStatic() {
}
public static int sum(int x, int y) {
return x + y;
}
public static int max(int x, int y) {
return x > y ? x : y;
}
public static int min(int x, int y) {
return x > y ? y : x;
}
}
Class, Object, Instance
- Class
public class Student {
private String name;
private int age;
private String grade;
}
- Object
Student st;
- 아직 변수가 구체적인 실체를 가리키지 않고 있는 상태
- Instance
- 객체가 실제로 생성되어 Heap Memory에 만들어진 상태
st = new Student();
좋은 정보 얻어갑니다, 감사합니다.