본문 바로가기
Programming Study

JAVA 클래스 멤버변수 초기화

by White,,JY 2018. 12. 29.
728x90
300x250

※ 클래스 멤버변수 초기화 방법 3가지 소개

 

1. 명시적 초기화(Explicit initialization) 

1
2
3
4
class Car {
    int door = 4;
    Engine e = new Engine();
}
cs

 

2. 생성자(Constructor)

1
2
3
4
5
6
7
8
9
10
11
class Car {
    String color;
    String gearType;
    int door;
    
    Car(String color, String gearType, int door) {
        this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
}
cs

3. 초기화 블럭(Initialization block)

   - 클래스 초기화 블럭 : 클래스 변수의 복잡한 초기화가 가능함

   - 인스턴스 초기화 블럭 : 생성자가 여러개일 경우 중복코드를 인스턴스 초기화 블럭을 이용하여 제거할 수 있음

1
2
3
4
5
6
7
8
9
public class BlockTest {
    static {    //class initialize block
        System.out.println("static initialize block");
    }
    
    {            //instance initialize block
        System.out.println("instance initialize block");
    }
}
cs

 

 

  초기화 블럭 실행 순서

1. 명시적 초기화

2. 클래스 초기화 블럭

3. 인스턴스 초기화 블럭

4. 생성자

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class BlockTest {
    static {    //class initialize block
        System.out.println("static initialize block");
    }
    
    {            //instance initialize block
        System.out.println("instance initialize block");
    }
    
    public BlockTest(){
        System.out.println("Constructor");
    }
    
    public static void main(String[] args) {
        System.out.println("[Create BlockTest instance 1]");
        BlockTest bt1 = new BlockTest();
        
        System.out.println("[Create BlockTest instance 2]");
        BlockTest bt2 = new BlockTest();        
    }
}
cs

 

 

 실행결과

static initialize bloc
[Create BlockTest instance 1]
instance initialize block
Constructor
[Create BlockTest instance 2]
instance initialize block
Constructor

 

 

 

728x90
300x250