[Java] 6. 객체지향 프로그래밍 1 #4 생성자(Constructor)

2022. 4. 28. 00:23JAVA/Language

5.1 생성자란?

생성자

  • 생성자는 인스턴스가 생성될 때 호출되는 '인스턴스 초기화' 메서드
  • 인스턴스 생성시 인스턴스의 필드멤버에 값을 초기화할 수 있음

 

생성자의 조건

  • 생성자의 이름은 클래스의 이름과 같아야함
  • 생성자는 리턴 값이 없음
클래스이름(타입 변수명, 타입 변수명, ...){
	// 인스턴스 변수의 초기화
}

class Card{
	String color;
    
    Card(){
    
    }
    Card(String color){
    	this.color = color;
    }
}

 

생성자의 특징

Card c = new Card();
  • 연산자 new에 의해서 메모리(heap)에 Card 클래스의 인스턴스가 생성됨
  • 생성자 Card()가 호출되어 수행됨
  • 연산자 new의 결과로, 생성된 Card 인스턴스의 주소가 반환되어 참조변수 c에 저장됨

 

2. 기본 생성자(default constructor)

  • 모든 클래스에는 하나 이상의 생성자가 정의되어 있음
  • 만약 클래스에 생성자가 하나도 정의되어 있지 않으면 컴파일러에 의해 공백 생성자를 자동 생성함

공백 생성자

클래스이름(){

}

Card(){

}

 

3. 매개변수가 있는 생성자

  • 생성자도 메서드처럼 매개변수를 선언하여 호출 시 값을 넘겨받아서 인스턴스의 필드멤버에 초기화 작업을 수행할 수 있음

매개변수가 있는 생성자 예제

public class Car {
	String color;		// 색상
	String gearType;	// 변속기 종류 - auto(자동), manual(수동)
	int door;			// 문의 개수
	
	public Car() {
		
	}
	
	public Car(String color, String gearType, int door) {
		this.color = color;
		this.gearType = gearType;
		this.door = door;
	}
}
public class Driver {
	public static void main(String[] args)
	{
		Car car1 = new Car();
		car1.color = "red";
		car1.gearType = "auto";
		car1.door = 4;
		
		Car car2 = new Car("blue", "manual", 2);
		
		System.out.printf("car1의 color=%s, gearType=%s, door=%d\n"
						, car1.color
						, car1.gearType
						, car1.door);
		
		System.out.printf("car2의 color=%s, gearType=%s, door=%d\n"
				, car2.color
				, car2.gearType
				, car2.door);		
	}
}
car1의 color=red, gearType=auto, door=4
car2의 color=blue, gearType=manual, door=2

 

4. 생성자에서 다른 생성자 호출하기 - this(), this

  • 같은 클래스의 멤버들간에 서로 호출할 수 있는 것처럼 생성자 간에도 서로 호출이 가능함
  • 생성자 간의 호출 조건
    1. 생성자의 이름으로 클래스 이름 대신 this를 사용함
    2. 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫줄에서만 호출이 가능함
public class Car {
	String color;		// 색상
	String gearType;	// 변속기 종류 - auto(자동), manual(수동)
	int door;			// 문의 개수
	
	public Car() {
		this("white", "auto", 4);
	}
	
	public Car(String color) {
		this(color, "auto", 4);
	}
	
	public Car(String color, String gearType, int door) {
		this.color = color;
		this.gearType = gearType;
		this.door = door;
	}
}

 

this

  • this : 인스턴스 자신을 가리키는 참조 변수, 인스턴스의 주소가 저장되어 있음
  • this(), this(매개변수) : 생성자, 같은 클래스의 다른 생성자를 호출할때 사용함

 

5. 생성자를 이용한 인스턴스의 복사

Car(Car c){
    color = c.color;
    gearType = c.gearType;
    door = c.door;
}

 

References

source code : https://github.com/yonghwankim-dev/java_study
Java의 정석, 남궁 성 지음