ocajp 자격증 (Oracle Certified Associate Ja
자바 static{} block 스태틱 블록의 의미
xemaker
2020. 3. 22. 09:34
저런 것을 초기화 블럭이라고 합니다.초기화 블럭(initialization block)
- 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화에 사용된다. 클래스가 처음 로딩될 때 한번만 수행된다.
- 인스턴스 초기화 블럭 : 인스턴스 변수의 복잡한 초기화에 사용된다. 인스턴스가 생성될때 마다 수행된다. (생성자보다 먼저 수행된다.)
class InitBlock{
static
{
/* 클래스 초기화 블럭 */
}
{
/* 인스턴스 초기화 블럭 */
}
}
보통 이런 형태인데요.
인스턴스 변수의 초기화는 주로 생성자를 사용하기 때문에, 인스턴스 초기화 블럭은 잘 사용되지 않는다. 대신 클래스의 모든 생성자에서 공통적으로 수행되어져야 하는 코드가 있는 경우 생성자에 넣지 않고 인스턴스 초기화 블럭에 넣어 두면 코드의 중복을 줄일 수 있어서 좋다.
class Car{
String color="";
String gearType="";
Car(){
System.out.println("Car 인스턴스 생성");
color="White";
gearType="Auto";
}
Car(String color, String gearType){
System.out.println("Car 인스턴스 생성");
this.color = color;
this.gearType=gearType;
}
public static void main(String[] args) {
new Car();
new Car("A","B");
}
}
실행결과:
Car 인스턴스 생성
Car 인스턴스 생성
설명:
main 메소드에 있는 2개의 생성자가 호출되면 "Car 인스턴스 생성" 이라고 2번 호출된다. 이렇게 중복되게 생성자에 있는 것을 인스턴스 초기화 블럭을 사용하면 코드 중복을 막을 수 있다.
이처럼 코드의 중복을 제거할 수 있습니다.
package staticblock;
class Car{
String color="";
String gearType="";
{ System.out.println("Car인스턴스 생성"); }
Car(){
color="White";
gearType="Auto";
}
Car(String color, String gearType){
this.color = color;
this.gearType=gearType;
}
public static void main(String[] args) {
new Car();
new Car("A","B");
}
}
실행결과:
Car인스턴스 생성
Car인스턴스 생성
설명:
main 메소드에서 new Car() 와 newCar("A","B"); 이렇게 생성자 2번을 호출했는데 {} 인스턴스 초기화 블럭에 의해서
Car 인스턴스 생성 이라고 2번 호출되서 print 하는것을 볼 수 있다.
package staticblock;
class BlockTest{
// 클래스 초기화 블럭
static {
System.out.println("static { }");
}
// 인스턴스 초기화 블럭
{
System.out.println("{ }");
}
public BlockTest(){
System.out.println("생성자");
}
public static void main(String args[]){
System.out.println("BlockTest bt = new BlockTest(); ");
BlockTest bt = new BlockTest();
System.out.println("BlockTset bt2 = new BlockTest();");
BlockTest b2 = new BlockTest();
}
}
실행결과:
static { }
BlockTest bt = new BlockTest();
{ }
생성자
BlockTset bt2 = new BlockTest();
{ }
생성자
설명:
static{} 즉 클래스 초기화 블럭에 의해 클래스가 처음 로딩될때 한번만 수행되었다.
{} 즉 인스턴스 초기화 블럭에 의해 인스턴스가 생성될 때 마다 호출이 되었고 생성자보다 먼저 수행이 되었다.
참고: