클래스 메소드의 정의와 호출
class NumberPrinter {
private int myNum = 0; // 객체를 생성할 때 메모리에 올라감(new할 때)
static void showInt(int n) { // 스캔할 때 메모리에 올라감
❌System.out.println(myNum);
// private int myNum = 0;가 메모리에 올라가기 전에 static이 먼저 올라가기 때문에, 메모리에 안올라간 인스턴스 변수는 찾을 수가 없다.
System.out.println(n);
}
static void showDouble(double n) {
System.out.println(n);
}
void setMyNumber(int n) {
myNum = n;
}
void showMyNumber() {
showInt(myNum); // 내부 접근
System.out.println(myNum);
// 객체 생성할 때 메모리에 올라가기 때문에 가능
}
}
public class ClassMethod {
public static void main(String[] args) {
// NumberPrinter를 먼저 스캔한다. 스캔할 때 static이 메모리에 올라간다.
NumberPrinter.showInt(20); // 외부 접근/클래스 이름으로 접근
System.out.println();
NumberPrinter np = new NumberPrinter();
np.showDouble(3.15); // 외부 접근/객체로 접근 가능
np.setMyNumber(75);
np.showMyNumber();
}
}
✔클래스 메소드로 정의하는 것이 옳은 경우
메모리 올라가는 순서가 다르기 때문이다.
그러하므로, 메모리 할당이 안된 인스턴스 변수를 static함수에서 사용할 수 없다.
⚠️static변수를 컨트롤 할 수 있는 것은 static함수!
class AAA {
int num = 0;
static void addNum(int n) {
num += n; //에러
} //static함수가 먼저 메모리에 올라가기 때문에
}
인스턴스보다 static이 메모리에 먼저 올라가기 때문에 둘 다 호출할 수 있다.
static은 스캔하면 바로 메모리에 올라가지만, 인스턴스 변수/함수는 객체 생성시 메모리 공간이 할당된다.
✔메소드 영역(method area)
✔힙 영역(heap)
✔스택 영역(stack)
스택 영역에 저장되는 메소드의 호출 정보를 스택 프레임(stack frame)