* 클래스 초기화 블럭 : 클래스변수의 복잡한 초기화에 사용되며 클래스가 로딩될 때 실행된다.
* 인스턴스 초기화 블럭 : 생성자에서 공통적으로 수행되는 작업에 사용되며 인스턴스가 생성될
때 마다 (생성자보다 먼저) 실행된다.
1.
class BlockTest {
int a;
static {
System.out.println("클래스 블럭"); // 클래스 초기화 블럭
}
{
System.out.println("블럭"); // 인스턴스 초기화 블럭
}
BlockTest() {
System.out.println("생성자"); // 생성자를 통해서 초기화
}
public static void main(String[] args)
{
BlockTest bt1=new BlockTest();
BlockTest bt2=new BlockTest();
}
}
클래스 블럭
블럭
생성자
블럭
생성자
2.
class Product {
static int count=0;
int serialNo;
{
++count;
serialNo=count; // 밑으로 가도 상관없다.
}
Product() { }
}
class ProductTest {
public static void main(String[] args) {
Product p1=new Product();
Product p2=new Product();
Product p3=new Product();
System.out.println("p1의 제품번호(serial no)는 "+ p1.serialNo);
System.out.println("p2의 제품번호(serial no)는 "+ p2.serialNo);
System.out.println("p3의 제품번호(serial no)는 "+ p3.serialNo);
System.out.println("생산된 제품의 수는 모두 "+ Product.count +"개 입니다.");
}
}
p1의 제품번호(serial no)는 1
p2의 제품번호(serial no)는 2
p3의 제품번호(serial no)는 3
생상된 제품의 수는 모두 3개 입니다.
3.
class Document {
static int count=0;
String name;
Document() {
this("제목없음"+ ++count); // this() : 같은 클래스의 다른생성자를 호출
}
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();
Document d4=new Document();
}
}
문서 제목없음1 가 생성되었습니다.
문서 자바.txt 가 생성되었습니다.
문서 제목없음2 가 생성되었습니다.
문서 제목없음3 가 생성되었습니다.
'Programming > Java' 카테고리의 다른 글
상속과 포함 (0) | 2011.01.22 |
---|---|
생성자 . this() . this (0) | 2011.01.17 |
메서드 오버로딩 (0) | 2011.01.17 |
클래스메서드와 인스턴스메서드 (0) | 2011.01.17 |
JVM 의 메모리구조 (0) | 2011.01.16 |