day11_CarTest3Ex13

육희영·2021년 10월 26일
0
package com.java1.day11;

//생성자를 이용한 인스턴스의 복사
class Car2 {
	String color; // 색상
	String gearType; // 변속기 종류 - auto(자동), manual(수동)
	int door; // 문의 개수

	Car2() { // 생성자의 이름으로 클래스이름대신 this를 사용한다.
		this("white", "auto", 4); // 다른 생성자를 호출할때 반드시 첫 줄에서만 호출이 가능하다.
	}

	Car2(Car2 c) { // 인스턴스의 복사를 위한 생성자.
		this.color = c.color;
		this.gearType = c.gearType;
		this.door = c.door;
	}

	Car2(String color, String gearType, int door) {
		this.color = color; // this는 자기자신을 의미한다.
		this.gearType = gearType;
		this.door = door;

	}

}

public class CarTest3Ex13 {

	public static void main(String[] args) {
		Car2 c1 = new Car2();
		Car2 c2 = new Car2(c1);// 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);

	}

}

출력결과

c1의 color=white, gearType=auto, door=4
c2의 color=white, gearType=auto, door=4
c1.door=100; 수행 후
c1의 color=white, gearType=auto, door=100
c2의 color=white, gearType=auto, door=4

0개의 댓글

관련 채용 정보