변수의 초기화
- 지역변수는 수동 초기화 해야함 (사용 전 꼭)
- 멤버변수 (iv, cv)는 자동 초기화 됨
Class InitTest {
int x;
int y = x;
void method1() {
int i;
int j = i;
}
}
멤버변수(iv, cv)의 초기화
- 명시적 초기화 (=, 간단한 초기화)
class Car {
int door = 4;
Engine e = new Engine();
}
- 참조형 변수는 null (기본값) 혹은 객체의 주소로 초기화 함
- 초기화 블럭 (복잡한 초기화)
- 인스턴스 초기화 블럭 : {}
- 클래스 초기화 블럭 : static {}
class StaticBlockTest {
static int[] arr = new int[10];
static {
for (int i = 0; i < arr.length;, i++) {
arr[i] = (int)(Math.random() * 10) + 1
}
}
- 생성자 (iv초기화, 복잡한 초기화)
Car(String color, String gearType, int door) {
this.color= color;
this.gearType = gearType;
this.door = door;
}
멤버변수의 초기화 시점
- 클래스 변수 초기화 시점 : 클래스가 처음 로딩될 때 단 한번
- 인스턴스 변수 초기화 시점 : 인스턴스가 생성될 때 마다
- 초기화 순서는 자동 -> 간단 -> 복잡
class InitTest {
static int cv = 1;
int iv = 1;
static { cv = 2; }
{ iv = 2; }
InitTest() {
iv = 3;
}
}
- 클래스 변수의 기본값 설정: cv = 0
- 클래스 변수의 명시적 초기화: cv = 1
- 클래스 초기화 블럭 실행: cv = 2
- 인스턴스 변수의 기본값 설정: iv = 0
- 인스턴스 변수의 명시적 초기화: iv = 1
- 인스턴스 초기화 블럭 실행: iv = 2
- 생성자 실행: iv = 3