[JAVA] static

집 가고 싶다.·2024년 1월 4일

JAVA

목록 보기
27/33
post-thumbnail

1. static 이해하기

  • 객체 간 공유 자원을 표현하는 static 키워드.
  • 모든 객체에서 공통으로 사용되는 값에 static을 사용.
public class Article {
    private static int count;      // 전체글수
    private static String category; // 카테고리
    private int num;                // 글번호
    private String title;           // 제목
    private String regDate;         // 날짜
}

2. 컴퓨터의 메모리 구조

  • 고정 영역:
    • 코드 영역: 프로그램 코드 저장.
    • 데이터 영역: 전역변수, static 변수 할당.
  • 동적 영역:
    • 힙 영역: 객체, 메모리 동적 할당.
    • 스택 영역: 함수 실행 파라미터, 지역변수.

3. 프로그램이 메모리를 사용하는 순서

  • 고정 영역:
    • 실행 파일 크기만큼 RAM 사용.
    • 크기 고정.
  • 동적 영역:
    • new 키워드로 객체, 배열 생성.
    • 메서드 호출 시 파라미터, 지역변수 생성 및 소멸.

4. static 데이터의 생성 위치

  • static 데이터는 데이터 영역에 생성.
  • 일반 멤버 변수, 객체는 힙 메모리에 생성.

5. static 메서드 사용시의 제약사항

  • static 메서드는 동적 메모리의 멤버 변수 사용 불가.
  • static이 아닌 일반 멤버 함수 호출 불가.

6. 멤버변수와 static 멤버변수의 차이

  • static 변수는 클래스 단위로 생성되므로 객체 생성과 상관 없이 클래스 이름으로 접근.
public class Article {
    private static int count;  // 전체글수
    public static void setCount(int count) {
        Article.count = count;
    }
    public static int getCount() {
        return Article.count;
    }
}

static을 통한 메모리 효율적 사용과 객체의 생성과 무관한 데이터 공유 가능.
예제 코드

// Article 클래스는 static 변수 count와 일반 변수들을 포함하며,
// Main 클래스에서 static 메서드와 일반 메서드를 통해 각각에 접근하는 예제입니다.
public class Article {
    private static int count;      // 전체글수
    private int num;               // 글번호
    private String title;          // 제목
    private String regDate;        // 날짜

    // static 메서드로 static 변수에 접근하는 예제
    public static void setCount(int count) {
        Article.count = count;
    }

    public static int getCount() {
        return Article.count;
    }

    // 일반 메서드로 일반 멤버 변수에 접근하는 예제
    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return this.title;
    }
}

public class Main {
    public static void main(String[] args) {
        // static 변수에 접근
        Article.setCount(10);
        System.out.println("전체 글 수: " + Article.getCount());

        // 객체 생성 및 일반 변수에 접근
        Article article = new Article();
        article.setTitle("제목");
        System.out.println("글 제목: " + article.getTitle());
    }
}

실행 결과

전체 글 수: 10
글 제목: 제목
profile
틀린거 있으면 알려주세요.

0개의 댓글