John's Code Journey

[JAVA] Static - 클래스가 공유하는 공간 본문

IT공부/JAVA

[JAVA] Static - 클래스가 공유하는 공간

Johnnnn 2025. 4. 23. 12:27
728x90

✅ static이란?

static은 "공유" 라는 개념
클래스에 소속되어 있어서 객체를 만들지 않아도 사용할 수 있는 멤버를 만들 때 사용함

 

💡 쉽게 말해서

  • 일반 변수/메서드: 객체(Object)를 만들어야 쓸 수 있음.
  • static 변수/메서드: 객체를 만들지 않고도 클래스 이름으로 바로 사용 가능!

📌 예시

public class Student {
    // static 변수 (모든 객체가 공유)
    static int count = 0;

    // 인스턴스 변수 (각 객체마다 따로 존재)
    String name;

    // 생성자
    public Student(String name) {
        this.name = name;
        count++; // 객체가 생성될 때마다 count 증가
    }

    // static 메서드
    public static void printCount() {
        System.out.println("총 학생 수: " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("철수");
        Student s2 = new Student("영희");

        // 객체 없이 클래스 이름으로 바로 접근 가능
        Student.printCount(); // 출력: 총 학생 수: 2
    }
}

🎯 정리

구분 static O static X
접근 방식 클래스명.변수 객체명.변수
메모리 프로그램 시작 시 할당 객체 생성 시 할당
대표 용도 공용 데이터, 유틸리티 메서드 객체별 데이터

📌 언제 static을 써야 할까?

✅ 1. 공통으로 사용하는 값이 있을 때

public class Config {
    public static String VERSION = "1.0.0";
}
  • Config.VERSION처럼 클래스 이름으로 바로 접근 가능
  • 프로그램 전반에서 버전 정보가 필요할 때 좋음

✅ 2. 객체와 무관한 기능을 만들고 싶을 때 (유틸리티 메서드)

public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
}

 

  • MathUtils.add(5, 3)처럼 객체 없이 바로 호출 가능
  • 계산, 변환, 포맷팅 같은 메서드 만들 때 자주 씀

✅ 3. 객체의 개수를 세고 싶을 때

public class User {
    static int userCount = 0;

    public User() {
        userCount++;
    }

    public static void printUserCount() {
        System.out.println("현재 사용자 수: " + userCount);
    }
}

 

 

  • 사용자 객체가 생성될 때마다 카운트가 올라가
  • 모든 객체가 같은 userCount를 공유함

⚠️ static의 주의점

문제점 설명
OOP 원칙 위반 객체지향은 객체 중심인데 static은 객체 없이도 동작함
상태 공유 위험 여러 객체가 같은 static 변수에 접근하면 값이 꼬일 수 있음
메모리 오래 점유 static은 프로그램이 끝날 때까지 메모리에 남아 있음

🧱 인스턴스 멤버 vs 클래스 멤버(static)

구분 인스턴스 멤버 클래스 멤버(static)
소속 객체(인스턴스)에 속함 클래스에 속함
메모리 할당 시점 객체가 생성될 때 프로그램 시작 시 클래스 로딩 시점에
접근 방법 객체명.변수명 클래스명.변수명 (또는 객체명도 가능하지만 권장 X)
예시 각 학생의 이름, 점수 등 전체 학생 수, 평균 점수 등
대표 키워드 this static

💡 간단한 예제

public class Student {
    // 인스턴스 멤버
    String name;
    int score;

    // 클래스 멤버 (static)
    static int studentCount = 0;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
        studentCount++; // 모든 객체가 공유
    }

    public void printInfo() {
        System.out.println("이름: " + name + ", 점수: " + score);
    }

    public static void printCount() {
        System.out.println("전체 학생 수: " + studentCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("지수", 90);
        Student s2 = new Student("정우", 80);

        // 인스턴스 멤버 사용
        s1.printInfo();  // 객체를 통해 사용

        // 클래스 멤버 사용
        Student.printCount();  // 클래스 이름으로 바로 호출
    }
}

 

📍 기억해야 할 핵심 포인트

인스턴스 멤버 (name, score)

  • 객체마다 다른 값을 가짐
  • 여러 객체가 있으면 각자 고유한 값을 유지함

클래스 멤버 (studentCount)

  • 모든 객체가 공유하는 값
  • 객체를 만들지 않아도 클래스 이름으로 접근 가능

'IT공부 > JAVA' 카테고리의 다른 글

[JAVA] interface - 표준화의 시작  (1) 2025.04.23
[JAVA] final - 변하지 않는 값  (0) 2025.04.23
[JAVA] 레퍼 클래스(Wrapper Class)  (1) 2025.04.17
[JAVA] JVM 메모리 구조  (0) 2025.04.17
[JAVA] 계산기 과제 Lv 2  (1) 2025.03.05