[JAVA] 생성자

안요한·2022년 5월 19일
0

JAVA

목록 보기
5/16

5.1 생성자란?

  • 생성자는 인스턴스가 생성될 때 호출되는 '인스턴스 초기화 메서드'이다.
  • 인스턴스변수의 초기화 작업에 사용.
  • 클래스 내에 선언되며, 메서드와 유사하지만 리턴값이 없다.

→ 1. 생성자의 이름은 클래스의 이름과 같아야 한다.

  1. 생성자는 리턴값이 없다.

Card클래스로 예를 들어보자

Card c = new Card();

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

5.2 기본 생성자

사실 모든 클래스에는 반드시 하나 이상의 생성자가 정의되어 있어야 한다.

하나도 정의하지 않으면 컴파일러가 제공해준다.

"기본 생성자가 컴파일러에 의해서 추가되는 경우는

                                     **클래스에 정의된 생성자가 하나도 없을 때 뿐이다."**

5.3 매개변수가 있는 생성자

Car인스턴스를 생성할 때, 생성자 Car()를 사용한다면, 인스턴스를 생성한 다음에

인스턴스 변수들을 따로 초기화 해주어야 하지만,

매개변수가 있는 생성자 Car(String color, String gearType, int door)를 사용한다면

인스턴스를 생성하는 동시에 원하는 값으로 초기화를 할 수 있게 된다.

  • 예제 6-24/CarTest.java
class Car {
	String color;		  //색상
	String gearType;	//변속기 종류
	int door;			    //문의 개수

	Car() {}
	Car(String c, String g, int d) {
		color = c;
		gearType = g;
		door = d;
	}
}

class CarTest {
	public static void main(String[] args) {
		Car c1 = new Car();
		c1.color = "white";
		c1.gearType = "auto";
		c1.door = 4;

		Car c2 = new Car("white", "auto", 4);

		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
	}
}

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

  • 생성자의 이름으로 클래스이름 대신 this를 사용한다.
  • 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫 줄에서만 호출이 가능하다.
class Car {
	String color;		
	String gearType;	
	int door;			

	Car() {  //생성자 첫 줄 호출
		this("white", "auto", 4);	 //클래스 이름 대신 this사용
	}

	Car(String color) {
		this(color, "auto", 4); //클래스 이름 대신 this사용
	}
	Car(String color, String gearType, int door) {
		this.color    = color;
		this.gearType = gearType;
		this.door     = door;
	}
}

class CarTest {
	public static void main(String[] args) {
		Car c1 = new Car();	
		Car c2 = new Car("blue");

		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
	}
}

"this : 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어 있다.

모든 인스턴스메서드에 지역변수로 숨겨진 채로 존재한다."

"this(),this(매개변수) : 생성자, 같은 클래스의 다른 생성자를 호출할 때 사용한다."

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

현재 사용하고 있는 인스턴스와 같은 상태를 갖는 인스턴스를 하나 더 만들고자 할 때 생성자를 이용할 수 있다.

class Car {
	String color;		
	String gearType;    
	int door;			

	Car() {
		this("white", "auto", 4);
	}

	//Car(Car c) {	//인스턴스의 복사를 위한 생성자
	//	color    = c.color;
	//	gearType = c.gearType;
	//	door     = c.door;
	//}
-> // 바로 위 코드보다 아래와 같이 다른 생성자를 호출하는 것이 바람직하다.
	Car(Car c) {
   // Car(String color, String gearType, int door)
			this(c.color, c.gearType, c.door);
	}

	Car(String color, String gearType, int door) {
		this.color    = color;
		this.gearType = gearType;
		this.door     = door;
	}
}
class CarTest {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car(c1);	//c1의 복사본 c2를 생성한다.
													//독립적으인 메모리 공간에 존재하기 때문에 c1값이 변경되어도
													//c2는 영향을 받지 않는다.	
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);

		c1.door=100;	// c1의 인스턴스변수 door의 값을 변경한다.
		System.out.println("c1.door=100; 수행 후");
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
	}
}

"인스턴스를 생성할 때는 다음의 2가지 사항을 결정해야한다."

  1. 클래스 - 어떤 클래스의 인스턴스를 생성할 것인가?
  2. 생성자 - 선택한 클래스의 어떤 생성자로 인스턴스를 생성할 것인가?
profile
걍이렇게돼브렀다리

0개의 댓글