클래스 생성자를 이용해서 다른 인스턴스를 복사하는 방법은 다음과 같다.
1.
class Car{
String color;
String gearType;
int door;
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
Car(Car c) {
this.color = c.color;
this.gearType = c.gearType;
this.door = c.door;
}
}
2.
class Car{
String color;
String gearType;
int door;
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
Car(Car c) {
this(c.color,c.gearType,c.door);
}
}
보시다 싶이 2번 코드가 훨씬 깨끗하고 재사용 성이 높다
'JAVA > [JAVA]' 카테고리의 다른 글
클래스 간의 관계 선택 팁 (0) | 2022.10.27 |
---|---|
초기화 블럭 (0) | 2022.10.24 |
생성자에서 다른 생성자 호출하기 (0) | 2022.10.24 |
Optional 개념 및 사용법 (0) | 2022.10.23 |
기본형 매개변수와 참조형 매개변수 (0) | 2022.10.23 |