OOP-11 : 변수의 초기화

이의준·2024년 5월 29일

Java

목록 보기
32/87

변수의 초기화

  • 지역변수는 수동 초기화 해야함 (사용 전 꼭)
  • 멤버변수 (iv, cv)는 자동 초기화 됨
Class InitTest {
	int x; // 인스턴스 변수
    int y = x; // 인스턴스 변수
    
    void method1() {
    	int i;  // 지역변수
        int j = i;  // (에러) 지역변수를 초기화 하지 않고 사용
    }
}

멤버변수(iv, cv)의 초기화

  1. 명시적 초기화 (=, 간단한 초기화)
class Car {
	int door = 4;				// 기본형 (primitive type) 변수의 초기화
    Engine e = new Engine();	// 참조형 (reference type) 변수의 초기화
}
  • 참조형 변수는 null (기본값) 혹은 객체의 주소로 초기화 함
  1. 초기화 블럭 (복잡한 초기화)
  • 인스턴스 초기화 블럭 : {}
  • 클래스 초기화 블럭 : static {}
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
        }
}
  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;
    }
}
  1. 클래스 변수의 기본값 설정: cv = 0
  2. 클래스 변수의 명시적 초기화: cv = 1
  3. 클래스 초기화 블럭 실행: cv = 2
  4. 인스턴스 변수의 기본값 설정: iv = 0
  5. 인스턴스 변수의 명시적 초기화: iv = 1
  6. 인스턴스 초기화 블럭 실행: iv = 2
  7. 생성자 실행: iv = 3

0개의 댓글