Notice
Recent Posts
Recent Comments
Link
반응형
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

To Be Develop

[Java] 자바에서 생성자와 static 블럭의 차이점 본문

dev/Java

[Java] 자바에서 생성자와 static 블럭의 차이점

To Be Develop 2024. 1. 28. 20:35
반응형

static 블록과 생성자는 각각 클래스와 인스턴스의 초기화를 다루는데 사용되며, 그들의 주요 차이점은 다음과 같습니다.

1. Static 블록:

  • static 블록은 클래스가 로딩될 때 실행되는 블록입니다. 클래스가 사용되기 전에 단 한 번만 실행됩니다.
  • static 블록은 클래스 수준의 작업에 사용되며, 주로 클래스 변수(static 변수)의 초기화나 클래스 수준의 초기화 작업을 수행할 때 활용됩니다.
  • static 블록은 인스턴스 생성과 무관하게 클래스 로딩 시에 실행됩니다.
public class MyClass {
    // static 변수
    private static int staticVariable;

    // static 블록
    static {
        System.out.println("Static block is executed.");
        staticVariable = 42;
    }
}

2. 생성자:

  • 생성자는 인스턴스가 생성될 때마다 호출되는 특별한 메서드로, 해당 인스턴스의 초기화 작업을 수행합니다.
  • 생성자는 인스턴스 레벨의 작업에 사용되며, 인스턴스 변수의 초기화나 특정 작업을 수행하는 데 활용됩니다.
  • 생성자는 객체가 생성될 때마다 호출되기 때문에 인스턴스 변수에 대한 초기화는 보통 생성자에서 이루어집니다.
public class MyClass {
    // 인스턴스 변수
    private int instanceVariable;

    // 생성자
    public MyClass(int initialValue) {
        System.out.println("Constructor is called.");
        this.instanceVariable = initialValue;
    }
}

차이점 예시:

public class Example {
    // static 변수
    private static int staticVariable;

    // 인스턴스 변수
    private int instanceVariable;

    // static 블록
    static {
        System.out.println("Static block is executed.");
        staticVariable = 42;
    }

    // 생성자
    public Example(int initialValue) {
        System.out.println("Constructor is called.");
        this.instanceVariable = initialValue;
    }

    public static void main(String[] args) {
        // 클래스의 객체를 생성하면서 생성자 호출
        Example obj = new Example(10);

        // 결과:
        // Static block is executed.
        // Constructor is called.
    }
}

이 예제에서 static 블록은 클래스가 로딩될 때 실행되어 staticVariable을 초기화하고, 생성자는 객체를 생성할 때 호출되어 instanceVariable을 초기화합니다. 둘은 서로 다른 시점에 실행되는 것이 주요 차이입니다. static 블록은 클래스 로딩 시, 생성자는 객체 생성 시에 실행됩니다.

반응형