본문 바로가기
java

0929_초기화블럭

by 신방동불주먹 2022. 9. 29.
  • 사용 목적 : 클래스의 멤버 변수 초기화

 

 

 

  1. 인스턴스 변수

 

- 형식 :  {}

- 초기화 진행 순서 : 기본값 → 명시적 초기화 → 인스턴스 초기화 블록 → 생성자

 

1) 객체 생성

public class Main{
	public static void main(String[] args) {
		Member m = new Member(88,99);
	}
}

 

public class Member {
	
	int x;
	int y;                      ---------- 1. 자동 초기화
	static int cv = 100;
	static int count;
	
	{ 
		x = 10;					---------- 2. 인스턴스 초기화 블럭		
		y = 20;
        System.out.println("인스턴스 초기화 블럭"+ x +","+ y);
	}
	
	Member(int x, int y){ 
		this.x = x;				---------- 3. 생성자 초기화
		this.y = y;
        System.out.println("생성자의 호출" + x +","+ y);
	}
	
}

-출력순서  :

인스턴스 초기화 블럭10,20
생성자의 호출88,99

최종값 : 88, 99

 

 

 

2. 클래스 변수

 

- 형식 :  static {}

- 초기화 진행 순서 : 기본값 → 명시적 초기화 → 클래스 초기화 블록

public class Member {
	
	int x;
	int y;
	static int cv = 100;
	static int count;
	
	static {
		count = 1000;
		System.out.println("static 초기화 블럭"+cv+","+count);
	}
	
	MemberInit(int x, int y){ 
		this.x = x;
		this.y = y;
		System.out.println("생성자의 호출" + x +","+ y);
	}
	
}

-출력순서  :

static 초기화 블럭100,1000
인스턴스 초기화 블럭10,20
생성자의 호출88,99

 

 

 

public class MemberInit {  //0929 ----8 초기화 블럭
	//멤버변수 초기화
	//자동초기화(변수 타입에 맞는 초깃값으로 자동 초기화) - 명시적초기화(=선언과 동시에 초기화) - 생성자에 의한 초기화  - 초기화 방법
	//초기화 블록이란 클래스 필드의 초기화만을 담당하는 중괄호({})로 둘러싸인 블록을 의미합니다.
	//1. 클래스 변수 : 기본값 → 명시적 초기화 → 클래스 초기화 블록
//2. 인스턴스 변수 : 기본값 → 명시적 초기화 → 인스턴스 초기화 블록 → 생성자
	
	
	int x;
	int y;
	static int cv = 100;
	static int count = 10;
	
	{ //인스턴스 초기화 블럭 : 객체가 생성될 때마다 호출 
		x = 10;
		y = 20;
		System.out.println("인스턴스 초기화 블럭"+x+","+y);
	}
	

	
	static { //static 초기화 블럭 : 객체 생성시 딱 한번만 호출
		count = 1000;
		System.out.println("static 초기화 블럭"+cv+","+count);
	}
	
	
	
	
	MemberInit(int x, int y){ //static 변수 안돼? 대상이아니야?

		this.x = x;
		this.y = y;
		System.out.println("생성자의 호출"+x+","+y);
		
	}
	
}

 

 

 

 

 

 

 

 

 

 

 

 

-------------------------초기화블럭 사용

 

 

public class Product {//0929 ----9 초기화 블럭의 사용
	static int count = 0;
	int serial;
	
	//인스턴스 블럭에서 스태틱 사용가능
	{
		++count; //static은 값이 공유되니까 
		serial = count;
	}
	
	
}
public class ProductTest { //0929 ----9 초기화 블럭의 사용
	//생성자를 호출하면 생성자가 호출되기 직전에 초기화 블럭이 호출된다.

	public static void main(String[] args) {

		Product p1 = new Product();
		Product p2 = new Product();
		Product p3 = new Product();
		
		System.out.println("총 생성된 객체의 수 : "+ Product.count);
		System.out.println("p1은 "+p1.serial + "생성됨");
		System.out.println("p2은 "+p2.serial + "생성됨");
		System.out.println("p2은 "+p3.serial + "생성됨");
		
	}

}

'java' 카테고리의 다른 글

Java - Open JDK 1.8 설치  (0) 2022.10.01
0929_클래스 구성(연습)  (0) 2022.09.29
0929_this. / this()  (0) 2022.09.29
0929_생성자  (0) 2022.09.29
[java] 오버로딩  (0) 2022.09.29