class InitTest{
int x; // 인스턴스 변수
int y = x; //인스턴스 변수
void method1(){
int i; // 지역변수
int j = i; // Error!! 지역변수를 초기화하지 않고 사용
}
}
class Car{
int door = 4; // 기본형(primitive type) 변수의 초기화
Engine e = new Engine(); // 참조형(reference type) 변수의 초기화
}
정리
1. 자동 초기화 (cv, iv 초기화)
2. 간단 초기화 (=)
3. 복잡 초기화 : cv의 경우 static { }, iv의 경우 생성자
class StaticBlockTest{
static int[] arr = new int[10]; // 명시적 초기화
static { // 클래스 초기화 블럭 - 배열 arr을 난수로 채운다.
for(int i = 0; i < arr.length; i++){
arr[i] = (int)(Math.random()*10) + 1;
}
}
}
class InitTest{
static int cv = 1; // 명시적 초기화
int iv = 1; // 명시적 초기화
static { cv = 2; } // 클래스 초기화 블럭
{ iv = 2; } // 인스턴스 초기화 블럭
InitTest() { // 생성자
iv = 3;
}
}
InitTest it = new InitTest();