Development Tip

생성자에서 정적 최종 필드 초기화

yourdevel 2020. 10. 6. 19:32
반응형

생성자에서 정적 최종 필드 초기화


public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final 변수가 생성자에서 한 번만 할당 될 수 있음을 의미합니다.
  • static 클래스 인스턴스임을 의미합니다.

왜 이것이 금지되었는지 알 수 없습니다. 이러한 키워드가 서로 간섭하는 부분은 무엇입니까?


생성자는 클래스의 인스턴스가 생성 될 때마다 호출됩니다. 따라서 위의 코드는 인스턴스가 생성 될 때마다 x 값이 다시 초기화됨을 의미합니다. 그러나 변수가 최종 (및 정적)으로 선언 되었기 때문에이 작업 만 수행 할 수 있습니다.

class A {    
    private static final int x;

    static {
        x = 5;
    }
}

그러나 정적을 제거하면 다음을 수행 할 수 있습니다.

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

아니면 이거:

class A {    
    private final int x;

    {
        x = 5;
    }
}

정적 최종 변수는 클래스가로드 될 때 초기화됩니다. 생성자는 훨씬 나중에 호출되거나 전혀 호출되지 않을 수 있습니다. 또한 생성자는 각 새 객체와 함께 여러 번 호출되므로 필드가 더 이상 최종이 될 수 없습니다.

정적 최종 필드를 초기화하기 위해 사용자 정의 로직이 필요한 경우 정적 블록에 넣으십시오.


개체를 두 번째로 인스턴스화 할 때 어떤 일이 발생하는지 생각해보십시오. AGAIN을 다시 설정하려고하는데, 이는 정적 결승으로 명시 적으로 금지되어 있습니다. 인스턴스가 아닌 전체 클래스에 대해 한 번만 설정할 수 있습니다.

선언 할 때 값을 설정해야합니다.

private static final x=5;

추가 논리 또는 더 복잡한 인스턴스화가 필요한 경우 정적 초기화 블록에서 수행 할 수 있습니다.


static변수가 응용 프로그램에서 고유함을 의미합니다. final한 번만 설정해야 함을 의미합니다.

생성자에서 설정하면 변수를 두 번 이상 설정할 수 있습니다.

따라서 직접 초기화하거나 초기화 할 정적 메서드를 제안해야합니다.


Final 은 생성자에서 초기화되어야 함을 의미하지 않습니다. 일반적으로 다음과 같이 수행됩니다.

 private static final int x = 5;

대신 정적 은 변수가 클래스의 여러 인스턴스를 통해 공유됨을 의미합니다. 예 :

public class Car {
   static String name;
   public Car(String name) {
      this.name = name;
   }
}

...

Car a = new Car("Volkswagen");
System.out.println(a.name); // Produces Volkswagen

Car b = new Car("Mercedes");
System.out.println(b.name); // Produces Mercedes
System.out.println(a.name); // Produces Mercedes

생각해보세요. 코드로이 작업을 수행 할 수 있습니다.

A a = new A();
A b = new A(); // Wrong... x is already initialised

x를 초기화하는 올바른 방법은 다음과 같습니다.

public class A 
{    
    private static final int x = 5;
}

또는

public class A 
{    
    private static final int x;

    static
    {
        x = 5;
    }
}

    public class StaticFinalExample {
  /*
   * Static final fields should be initialized either in
   * static blocks or at the time of declaration only
   * Reason : They variables are like the utility fields which should be accessible
   * before object creation only once.
   */
  static final int x;

  /*
   * Final variables shuould be initialized either at the time of declaration or
   * in initialization block or constructor only as they are not accessible in static block
   */
  final int y;

  /*
   * Static variables can be initialized either at the time of declaration or
   * in initialization or constructor or static block. Since the default value is given to the
   * static variables by compiler, so it depends on when you need the value
   * depending on that you can initialize the variable appropriately
   * An example of this is shown below in the main method
   */
  static int z;

  static {
    x = 20; // Correct
  }
  {
    y = 40; // Correct
  }
  StaticFinalExample() {
    z = 50; // Correct
  }
  public static void main (String args[]) {
    System.out.println("Before Initialization in Constructor" + z);   // It will print 0
    System.out.println("After Initializtion in Constructor" + new StaticFinalExample().z); // It will print 50
  }
}

참고 URL : https://stackoverflow.com/questions/5093744/initialize-a-static-final-field-in-the-constructor

반응형