Product.java
package kr.co.kihd.initialize;
public class Product {
static int number = 0; //공유
int countNo; //인스턴스별 개별생성
int[] arr = new int[10];
//정적 초기화 블럭(단, 한번만 실행됨)
static {
System.out.println("정적 초기화블럭 호출됨");
}
//인스턴스 초기화 블럭(정정멤버 사용가능함)
{
System.out.println("인스턴스 초기화블럭 호출됨");
++number;
this.countNo = Product.number;
for(int i = 0; i<arr.length; i++) {
this.arr[i] = (int)(Math.random()*10)+1;
}
}
public Product() {
System.out.println("기본생성자 호출됨");
}
}
ProductTest.java
package kr.co.kihd.initialize;
import java.util.Arrays;
public class ProductTest {
public static void main(String[] args) {
Product product1 = new Product();
Product product2 = new Product();
Product product3 = new Product();
System.out.println(
" Product.number : " + Product.number +
" countNo : "+product1.countNo);
System.out.println(
" Product.number : " + Product.number +
" countNo : "+product2.countNo);
System.out.println(
" Product.number : " + Product.number +
" countNo : "+product3.countNo);
System.out.println(Arrays.toString(product1.arr));
System.out.println(Arrays.toString(product2.arr));
System.out.println(Arrays.toString(product3.arr));
}
}