멤버변수와 배열의 초기화는 선택적이지만, 지역변수의 초기화는 필수적이다.
class InitTest {
int x; // 인스턴스 변수: 자동적으로 int형의 기본값인 0으로 초기화
int y = x; // 인스턴스 변수: x의 값에 따라 y에도 0이 저장된다.
void method() {
int i; // 지역변수: 자동으로 초기화되지 않음
int j = i; // error: 지역변수 i의 초기화 필요
}
}
명시적 초기화란, 변수를 선언과 동시에 초기화하는 것을 말한다.
class Car {
int door = 4; // 기본형 변수의 초기화
Engine e = new Engine(); // 참조형 변수의 초기화
}
초기화 작업이 복잡하여 명시적 초기화만으로는 부족한 경우 초기화 블럭을 사용한다.
class BlockTest {
// 클래스 초기화 블럭
static {
System.out.println("클래스 초기화 블럭");
}
// 인스턴스 초기화 블럭
{
System.out.println("인스턴스 초기화 블럭");
}
// 생성자
public BlockTest() {
System.out.println("생성자");
}
public static void main(String args[]) {
BlockTest bt = new BlockTest();
BlockTest bt2 = new BlockTest();
}
}
/* 실행 결과
클래스 초기화 블럭
인스턴스 초기화 블럭
생성자
인스턴스 초기화 블럭
생성자
*/
class Document {
static int count = 0; // 문서명이 없는 인스턴스의 수를 누적해서 저장하기 위한 변수
String name;
Document() { // 문서명이 없는 기본 생성자
this("제목없음" + ++count);
}
Document(String name) { // 문서명을 매개변수로 받는 생성자
this.name = name;
System.out.println("문서 " + this.name + "가 생성되었습니다.");
}
}
class DocumentTest {
public static void main(String args[]) {
Document d1 = new Document();
Document d2 = new Document("자바.txt");
Document d3 = new Document();
}
}
/* 실행결과
문서 제목없음1가 생성되었습니다.
문서 자바.txt가 생성되었습니다.
문서 제목없음2가 생성되었습니다.
*/