Java/강의

[📙 Java 문법 종합반] 2-4. static - 클래스가 공유하는 공간

가지코딩 2025. 4. 15. 17:16

📙 목차

  1. Static
  2. 인스턴스 멤버(인스턴스 변수 + 인스턴스 메서드)
  3. 클래스 멤버(클래스 변수 + 클래스 메서드)
  4. 전체 코드 살펴보기
  5. Static 사용 시 주의사항

🧡 학습 목표

  • static 이 무엇인지 학습합니다.
  • 인스턴스 멤버와 클래스 멤버가 무엇인지 학습합니다.

1. Static

Static 이란?

  • static 키워드는 모든 객체가 함께 사용하는 변수나 메서드를 만들때 사용된다.
  • 객체(인스턴스)를 만들지 않아도 클래스 이름만으로 바로 사용할 수 있다.
  • 모든 객체가 같은 값을 공유한다.
  • static 변수와 메서드는 한 번만 생성되고 Method Area(메서드영역) 에 저장된다.

 

Static 활용

  • static 키워드는 변수, 메서드에 붙일 수 있다.
  • static 키워드로 선언된 변수와 메서드는 MethodArea 에 저장된다.
  • 각 객체(인스턴스)는 클래스 영역에 저장된 데이터를 활용할 수 있다.

 

class Person {
    // ✅ static 변수
    static int population = 0;

    // ✅ static 메서드
    static void printPopulation() {
        System.out.println("현재 인구 수: " + population);
    }
}

2. 인스턴스 멤버(인스턴스 변수 + 인스턴스 메서드)

인스턴스 멤버란?

  • 객체를 만들때 마다 생성되는 변수와 메서드
  • 객체(인스턴스)를 생성한 후에만 사용할 수 있다.
  • 각 객체가 개별적으로 값을 가진다. (공유되지 않음)
  • 인스턴스는 Heap 영역에 위치한다.

 

 

인스턴스 변수

class Person {
    String name; // ✅ 인스턴스 변수
}
public class Main {
    public static void main(String[] args) {
        Person p1 = new Person(); // p1 객체 생성
        p1.name = "gygim"; // ✅ p1 객체의 데이터에 접근

        Person p2 = new Person(); // p2 객체 생성
        p2.name = "Steve"; // ✅ p2 객체의 데이터에 접근
    }
}

 

 

인스턴스 메서드

class Person {
    String name;

    void printName() { // ✅ 인스턴스 메서드
        System.out.println("나의 이름은 " + this.name + "입니다.");
    }
}
class Person {
    String name;

    void printName() { // ✅ 인스턴스 메서드
        System.out.println("나의 이름은 " + this.name + "입니다.");
    }
}

3. 클래스 멤버(클래스 변수 + 클래스 메서드)

클래스 멤버란?

  • 클래스 자체에 속하는 변수와 메서드
  • static 키워드를 사용해서 선언한다.
  • 해당 클래스로 만들어진 객체가 공유해서 사용할 수 있다.
  • 클래스가 로드될때 Method Area 에 적재된다.
  • 객체 생성 없이 사용 가능하다.

 

 

클래스 변수

class Person {
    static int population = 0; // ✅ 클래스 변수
}
public class Main {
    public static void main(String[] args) {

        // ✅ 객체 생성 전에도 클래스 레벨에서 직접 접근가능
        System.out.println("현재 인구 수: " + Person.population);

        Person p1 = new Person();
        Person p2 = new Person();

        // ✅ 모든 객체가 하나의 값을 공유
        System.out.println("현재 인구 수: " + Person.population);
    }
}

 

 

클래스 메서드

class Person {
    static int population = 0;

    public Person(String name) {
        this.name = name;
        population++; // 생성자 호출시 populataion 1 증가
    }

    static void printPopulation() {
        System.out.println("현재 인구 수: " + population); // ✅ 클래스 메서드
    }
}
public class Main {
    public static void main(String[] args) {

        // ✅ 객체생성 여부에 상관없이 사용 가능
        Person.printPopulation(); // 현재 인구 수: 0

        Person p1 = new Person("gygim"); // 생성시마다 population 1 증가
        Person p2 = new Person("Steve"); // 생성시마다 population 1 증가

        Person.printPopulation(); // 현재 인구 수: 2
    }
}

4. 전체 코드 살펴보기

  • static 으로 선언된 변수와 메서드는 객체에서 공용으로 사용 가능하다.
public class Person {
    static int population = 0; // 클래스 변수 (모든 객체가 공유)
    String name; // 인스턴스 변수

    public Person(String name) {
        this.name = name;
        population++; // 생성자 호출시 populataion 1 증가
    }

    public void printName() {
        System.out.println("이름: " + name);
    }

    public static void printPopulation() { // 클래스 메서드
        System.out.println("현재 인구 수: " + population);
    }
}
public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("gygim");
        Person p2 = new Person("Steve");

        p1.printName();  // 인스턴스메서드는 객체 인스턴스화 이후에 호출 가능
        p2.printName();

        // 클래스 메서드는 클래스 이름으로 호출 가능
        Person.printPopulation();  // "현재 인구 수: 2"
    }
}

 


5. Static 사용 시 주의사항

 

static 은 공유가 필요한 곳에 사용해야 한다.

public class Student {
    static String name; // ⚠️ 모든 객체가 동일한 name을 공유 (위험)

    public Student(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println("이름: " + name);
    }
}
public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("gygim");
        Student s2 = new Student("Steve");

        s1.printName();  // ⚠️ "이름: Steve"
        s2.printName();  // ⚠️ "이름: Steve"
    }
}

 

 

static 메서드에서는 인스턴스 변수에 접근할 수 없다.

public class Person {
    String name;

    public static void staticMethod() {
        System.out.println(this.name);  // ⚠️ 오류 발생
    }
}

 

 

static 은 꼭 필요할 때만 사용해야 한다.

  • static 변수와 메서드는 프로그램이 종료될 때까지 메모리에 유지된다.
  • 너무 많은 static 남용하면 메모리 낭비로 이어진다.