class Address {
Address(String address, String phone) {
this.address = address;
this.phone = phone;
}
public String address;
public String phon
}
class User {
private String name;
private Address address;
User(String name, String address, String phone) {
this.name = name;
this.address = new Address(address, phone);
}
public Address getAddress() {
return address;
}
public String getName() {
return name;
}
// 얕은 복사로 인해 동일한 참조자를 사용하게 된다.(사이드 이펙트)
public void copy(User rhs) {
this.name = rhs.name;
this.address = rhs.address;
}
}
public class Main {
public static void main(String[] args) {
User user1 = new User("Hosung","Hanam", "010-1111-1111");
User user2 = new User("Hoon","Seoul", "010-2222-2222");
System.out.println(user1.getName());
System.out.println(user1.getAddress().address);
System.out.println(user1.getAddress().phone);
user1.copy(user2);
user2.getAddress().phone = "010-3333-3333";
user2.getAddress().address = "Busan";
System.out.println(user1.getName());
System.out.println(user1.getAddress().address);
System.out.println(user1.getAddress().phone);
}
}
...
// String 클래스는 레퍼런스 타입이지만 불변객체로 설계된 특별한 클래스이기 때문에, 문제가 안난다.
public void copy(User rhs) {
this.name = rhs.name;
//this.address = rhs.address;
this.address.address = rhs.address.address;
this.address.phone = rhs.address.phone;
}
...
class-name(class-name rhs)
class MyTest {
private int[] array = null;
public MyTest(int size) {
array = new int[size];
}
// 복사 생성자
public MyTest(MyTest rhs) {
this(rhs.array.length);
this.deepCopy(rhs);
}
public int getAt(int index) {
return array[index];
}
public void setAt(int index, int value) {
array[index] = value;
}
public void shallowCopy(MyTest rhs) {
array = rhs.array;
}
public void deepCopy(MyTest rhs) {
for(int i = 0; i < rhs.array.length; ++i)
array[i] = rhs.array[i];
}
}
public class Main {
public static void main(String[] args) {
MyTest t1 = new MyTest(3);
t1.setAt(0, 10);
t1.setAt(1, 20);
t1.setAt(2, 30);
MyTest t2 = new MyTest(3);
t2.shallowCopy(t1);
MyTest t3 = new MyTest(3);
t3.deepCopy(t1);
MyTest t4 = new MyTest(t1);
t1.setAt(0, -1);
System.out.println("t1[0]: " + t1.getAt(0)); // -1
System.out.println("t2[0]: " + t2.getAt(0)); // -1
System.out.println("t3[0]: " + t3.getAt(0)); // 10
System.out.println("t4[0]: " + t4.getAt(0)); // 10
}
}