Static 변수

행복한 콩🌳·2023년 2월 20일
0

JAVA

목록 보기
15/26

Static 변수의 정의와 사용법

[static 에약어] [자료형] [변수 이름]
static.     int     serialNum;
  • 여러 개의 인스턴스가 같은 메모리의 값을 공유하기 위해 사용

  • 인스턴스는 클래스에서 생성됨, 각각의 메모리를 가짐

  • static이라는 변수를 사용하면 따로 정적메모리[데이터 영역]에 저장됨

  • static 변수는 인스턴스가 생성될 때 마다 다른 메모리를 가지는 것이 아니라 프로그램이 메모리에 로드될 때 데이터 영역의 메모리에 생성 됨

  • 인스턴스는 힙 메모리에 생성된다.
  • 따라서 인스턴스의 생성과 관계없이 클래스 이름으로 직접 참조함
// serialNum이 static 변수
Student.serialNum = 100;
  • 클래스 변수라고 함
  • 멤버변수는 다른말로 인스턴스 변수라고 함!

static 메서드에서는 인스턴스 변수를 쓸 수 없다!

[StudentTest1]
package staticExample;

public class StudentTest1 {

    public static void 출main(String[] args) {
        Student studentJ = new Student();
        System.out.println(studentJ.studentId);

        Student studentT = new Student();
        System.out.println(studentT.studentId);

//        System.out.println(studentJ.getSerialNum());
//        System.out.println(studentT.getSerialNum());
        // static 변수는 보통 클래스 이름으로 참조함
        System.out.println(Student.getSerialNum());

    }
}
[Student.java]
package staticExample;

public class Student {
    private  static int serialNum = 10000;

    int studentId;
    String studentName;

    // 학생이 증가하면 생성자가 호출
    public Student(){
        serialNum++;
        studentId = serialNum;
    }
    public static int getSerialNum(){
        // 지역 변수                                    -> 생성 시기
        //                                              해당 메서드 생성 후 생성 메서드 실행 후 삭제됨 [스택]
        int i = 10;

        i++;
        System.out.println(i);

        // static 메서드에서는 인스턴스 변수를 사용할 수 없음
        // 인스턴스 변수                                  -> 생성 시기
        //                                               인스턴스가 new 되었을 때 생성됨 [힙], 생성되지 않은 인스턴스 변수 사용의 위험이 있으므로 static 메서드에서는 인스턴스 변수 사용 불가
        //                                               인스턴스 생성과 관계 없이 클래스 이름으로 직접 메서드 호출
        // studentName = "단친햄";

        // static 변수
        return serialNum;
    }
}
[StaticEx.java]
package staticExample;

public class StaticEx {

    // 학생들에게 학번 부여
    // 학번 기준값 10000
    private static int serialNum = 10000;
    int studentId;
    String studentName;
}

profile
매일매일 조금씩 모여 숲이 되자🐣

0개의 댓글