[JAVA] static과 메모리의 관계

정원석·2024년 3월 22일

🛶 메인(시작) 클래스는 왜 객체생성(new) 없이 실행되는가?

public class StaticTest {
    public static void main(String[] args) {
        System.out.println("Hello Java");
    }
}
  1. static 키워드가 붙은 멤버들은 정해진 메모리(ststic-zone)위치에 한번 자동으로 로딩 한다.
  2. JVM이 static-zone에서 main()메서드를 호출한다.
  3. 호출된 메서드를 Call Stack Frame Area(Stack Area)에 push한 뒤 동작을 시작한다.
public class StaticTest{
    public static void main(string[] args){
        int a=10;
        int b=20;
        int sum= StaticTest.hap(a,b);
        System.out.println(sum);
    }
    public static int hap(int a, int b){
        int v=a+b;
        return v;
    }
}

  • StackTest클래스의 main 메서드와 hap 메서드가 메모리(ststic-zone)에 할당된다.
  • 메서드 호출은 Stack 메모리 에서 이루어진다.
  • 메서드가 호출될 때마다 스택에 새로운 프레임이 생성된다.
  • main 메서드에서 hap을 호출하면, hap메서드의 프레임이 스택에 쌓인다.
  • hap 메서드가 실행을 마치고 반환할 때, 해당 프레임은 스택에서 제거된다.

🎄 static 메서드 접근방법

//main 클래스
public class StaticAccess {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        // MyUtil
        int sum = MyUtil.hap(a, b); //클래스 이름.호출메서드
        System.out.println(sum);
    }
}
//MyUtil 클래스
public class MyUtil {
    public static int hap(int a, int b){
        int v = a + b;
        return v;
    }
}

static멤버는 클래스를 사용하는 시점에서 자동으로 static-zone에 로딩된다. 따라서 new를 이용해서 객체를 생성할 필요가 없다.

⛱ none static 메서드 접근방법

//main 클래스
public class NoneStaticAccess {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        //MyUtil1
        //객체 생성
        MyUtil1 my1 = new MyUtil1();
        int sum = my1.hap(a,b);
        System.out.println(sum); // 30
    }
}
//none static 클래스
public class MyUtil1 {
    public int hap(int a, int b){
        int v = a + b;
        return v;
    }
}

평소 사용하던 대로 객체 생성 후 메모리에서 메서드를 불러와서 사용한다.

🎪 클래스의 모든 메서드가 static일 때 바람직한 호출방법

//main 클래스
public class AllStaticTest{
    public static void main(String[ ] args){
        //AllStatic st=new AllStatic();
        System.out.println(AllStatic.hap(10,20));
        System.out.println(AllStatic.max(10,20));
        System.out.println(AllStatic.min(10,20));
    }
}
//static 메서드 클래스
public class AllStatic{
    private AllStatic(){
    }
    public static int hap(int a, int b){
        int v=a+b;
        return v;
    }
    public static int max(int a, int b){
        return a>b ? a : b;
    }
    public static int min(int a, int b){
        return a<b ? a : b;
    }
}

일 때 AllStatic st = new AllStatic(); 을 통해 객체를 생성할 필요 없이 클래스 . 메서드 를 통해 메서드를 사용할 수 있었다.
하지만 AllStatic st = new AllStatic(); 를 통해 객체를 생성하고 st . 메서드를 통해서도 메서드를 호출할 수 있지만 바람직하지 않은 방법이다. 이를 막기 위해 생성자에 private 처리를 하여 메인 클래스에서 객체생성을 못하도록 막는다.

  • private 생성자를 가지고 있는 클래스도 있다.
    ex) System, Math 등
  • 생성자는 반드시 public이다. (잘못된 설명)

🍞 Class, Object, Instance 구분하기

Class(클래스)

객체를 모델링 하는 도구(설계도)

public class Student {
private String name;
private String dept;
private int age;
private String email;
private int year;
private String phone;
public Student() {
}
//이하 생략
}

Object(객체)

클래스를 통해 선언되는 변수

Instance(인스턴스, 실체)

객체 생성에 의해 메모리(Heap Memory)에 만들어진 객체 인스턴스(instance)라고 한다.

profile
Back-End-Dev

0개의 댓글