[CH6. 객체지향프로그래밍1 ] 변수의 초기화

6. 변수의 초기화

6.1 변수의 초기화

변수를 선언하고 처읍으로 값을 저장하는것.
가능하면 선언과 동시에 초기화 하는게 바람직.

  • 멤버변수(클래스변수와 인스턴스 변수)와 배열의 초기화는 선택적이지만,
    지역변수는 반드시 초기화 후 사용해야함.

멤버변수 추기화 방법

  1. 명시적 초기화
  2. 생성자
  3. 초기화 블럭
    • 인스턴스 초기화 블럭: 인스턴스변수를 초기화 하는데 사용
    • 클래스 초기화 블럭: 클래스를 초기화 하는데 사용

6.2 명시적 초기화

변수 선언과 동시에 초기화 하는것

1
2
3
4
class Car{
int door= 4; //기본형 변수 초기화
Engine = new Engine(); // 참조형 변수 초기화
}

6. 3 초기화 블럭

  • 초기화 블럭 - 클래스변수의 복잡한 초기화에 사용
  • 인스턴스 초기화 블럭 - 인스턴스 변수의 복잡한 초기화에 사용
1
2
3
4
class InitBlock{
static{/* 클래스 초기화 블럭*/}
{/*인스턴스 초기화 블럭 */}
}

클래스 초기화 블럭은 클래스가 메모리에 올라가 갈 때 한번만 수행.
인스턴스 초기화는 인스턴스 생성될때 생성자보다 먼저 수행됨.

1
2
3
4
5
6
7
8
9
10
Car(){
System.out.println("Car인스턴스가 생성되었습니다.");
color= "withe";
gearType="auto";
}
Car(String color, String gearType){
System.out.println("Car인스턴스가 생성되었습니다.");
this.color= color;
this.gearType=gearType;
}

동일한 “Car인스턴스가 생성되었습니다.” 처리를 인스턴스 블럭으로 아래와 같이 처리

1
2
3
4
5
6
7
8
9
10
{ System.out.println("Car인스턴스가 생성되었습니다."); }

Car(){
color= "withe";
gearType="auto";
}
Car(String color, String gearType){
this.color= color;
this.gearType=gearType;
}

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

  • 클래스 변수 초기화 시점 - 클래스가 처음 로딩될 때 한번 초기화
  • 인스턴스 변수의 초기화 시점 - 인스턴스가 생성될 때마다 각 인스턴스별로 초기화 이루어짐

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

  • 인스턴스 변수 초기화 순서 : 기본값 -> 명시적 초기화 -> 인스턴스초기화 블럭 -> 생성자
1
2
3
4
5
6
7
8
9
10
11
class Product{
static int count =0; //생성된 인스턴스 수를 저장하기 위한 변수
int serialNo; //인스턴스 고유 번호

{
++count;
serialNo = count; // Product인스턴스가 생성될 때마다 count 값을 1증가시켜 serialNo에 저장
}

public product(){}
}

댓글

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×