English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java의 기본 생성자에서 static 변수가 초기화되었는가요?

스태틱 파일/변수는 해당 클래스에 속하며, 클래스와 함께 메모리에 로드됩니다. 객체를 생성하지 않고도 호출할 수 있습니다. (클래스 이름을 참조하여 사용). 클래스 전체에서 스타틱 필드의 복사본이 하나만 있으며, 즉, 스타틱 필드의 값은 모든 객체에서 동일합니다. static 키워드를 사용하여 스타틱 필드를 정의할 수 있습니다.

예제

public class Sample{
   static int num = 50;
   public void demo(){
      System.out.println("demo 메서드에서 num의 값 ");+ Sample.num);
   }
   public static void main(String args[]){
      System.out.println("main 메서드에서 num의 값 ");+ Sample.num);
      new Sample().demo();
   }
}

출력 결과

main 메서드에서 num의 값 50
demo 메서드에서 num의 값 50

스태틱 변수의 초기화

클래스에서 스타틱 변수를 선언했을 때, 그것들이 초기화되지 않았다면, 인스턴스 변수와 같이 기본 생성자의 기본 값으로 초기화됩니다. 컴파일러는 기본 생성자에서 기본 값을 사용합니다.

예제

public class Sample{
   static int num;
   static String str;
   static float fl;
   static boolean bool;
   public static void main(String args[]){
      System.out.println(Sample.num);
      System.out.println(Sample.str);
      System.out.println(Sample.fl);
      System.out.println(Sample.bool);
   }
}

출력 결과

0
null
0.0
false

스태틱 변수의 초기화

하지만, static 인스턴스 변수를 선언했을 때 final Java 컴파일러는 기본 생성자에서 초기화하지 않고, static과 final 변수를 초기화해야 합니다. 컴파일하지 않으면 오류가 발생합니다.

예제

public class Sample{
   final static int num;
   final static String str;
   final static float fl;
   final static boolean bool;
   public static void main(String args[]){
      System.out.println(Sample.num);
      System.out.println(Sample.str);
      System.out.println(Sample.fl);
      System.out.println(Sample.bool);
   }
}

컴파일 시 오류

Sample.java:2: 오류: 변수 num은 기본 생성자에서 초기화되지 않았습니다
   final static int num;
^
Sample.java:3: 오류: 변수 str은 기본 생성자에서 초기화되지 않았습니다
   final static String str;
^
Sample.java:4: error: variable fl not initialized in the default constructor
   final static float fl;
^
Sample.java:5: error: variable bool not initialized in the default constructor
   final static boolean bool;
^
4 에러

구조 함수에서 최종 변수에 값을 할당할 수 없습니다.-

예제

public class Sample{
   final static int num;
   Sample(){
      num =;100;
   }
}

출력 결과

Sample.java:4: error: cannot assign a value to final variable num
   num =;100;
^
1 에러

정적 최종 변수를 초기화하는 유일한 방법은 정적 블록입니다.

정적 블록은 코드에서 정적 키워드를 사용하는 블록입니다. 일반적으로 이들은 정적 멤버를 초기화하는 데 사용됩니다. JVM은 클래스를 로드할 때 메인 메서드 전에 정적 블록을 실행합니다.

예제

public class Sample{
   final static int num;
   final static String str;
   final static float fl;
   final static boolean bool;
   static{
      num =;100;
      str = "krishna";
      fl =;100.25f;
      bool = true;
   }
   public static void main(String args[]){
      System.out.println(Sample.num);
      System.out.println(Sample.str);
      System.out.println(Sample.fl);
      System.out.println(Sample.bool);
   }
}

출력 결과

100
krishna
100.25
true
당신이 좋아할 만한 것