Java/The Java Language

Static and Nostatic Initializer blocks

Steven J.S Min 2013. 2. 6. 16:38

이 코드블럭은 특정 메소드에 속해진 것이 아니지만 이블럭은 Constructor가 실행될때 단 한번 수행되어지거나

코드블럭에 static이라고 선언된 경우 클래스가 로딩될때 한번 수행되어진다.

따라서 static 변수를 초기화 하거나 실행 프로그램의 초기화 용도록 사용하면 요긴하겠다.

 

일반 코드블럭의 예

package test;

 

import java.util.Properties;

 

public class MyClass {

 

       Properties myProps = new Properties();

       // set up myProps

       {

              myProps.put("food", "bar");

              myProps.put("boo", "gee");

       }

       int a = 5;

       // TODO....

}

 

Static 코드블럭의 예

package test;

 

import java.awt.Color;

import java.util.Hashtable;

 

public class ColorWheel {

 

       static Hashtable colors = new Hashtable();

 

       // set up colors

       static {

              colors.put("Red", Color.red);

              colors.put("Greed", Color.green);

              colors.put("Blue", Color.blue);

              // TODO....

       }

 

}