seung_nari 2022. 1. 19. 19:50

멤버변수의 초기화 시기와 순서

 

클래스변수의 초기화시점 : 클래스가 처음 로딩될 때 단 한번 초기화 된다.

인스턴스변수의 초기화시점 : 인스턴스가 생성될 때마다 각 인스턴스별로 초기화가 이루어진다.

 

클래스변수의 초기화순서 : 기본값 -> 명시적초기화 -> 클래스 초기화 블럭

인스턴스변수의 초기화순서 : 기본값 -> 명시적초기화 -> 인스턴스 초기화 블럭 -> 생성자

 

public class InitTest {
	public static void main(String[] args) {
		System.out.println(Init.cnt);
		
		System.out.println("============");
		Init init = new Init();
		System.out.println("============");
		System.out.println(init.i);
		System.out.println(init.i);
		System.out.println("============");
		System.out.println(Init.cnt);
	}
}

class Init{
	static int cnt = 1;
	static int count() {
		System.out.println("count().cnt :: " + cnt);
		return cnt++;
	}
	
	static int si = count();
	
	int i = count();
}

 

클래스 초기화

static이 앞에 적혀 있는 클래스 메서드 및 변수만 초기화

 

인스턴스 초기화

static이 적혀 있지 않은 클래스 메서드 및 변수만 초기화