-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathPerson.java
More file actions
52 lines (44 loc) · 1.52 KB
/
Person.java
File metadata and controls
52 lines (44 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package ShallowVsDeepCopy;
class Address implements Cloneable {
String city;
String country;
Address(String city, String country) {
this.city = city;
this.country = country;
}
// Deep copy
protected Object clone() throws CloneNotSupportedException {
return new Address(this.city, this.country);
}
}
class Person implements Cloneable {
String name;
Address address;
Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Deep copy
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) this.address.clone();
return cloned;
}
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("Pune", "India");
Person person1 = new Person("John", address);
Person person2 = (Person) person1.clone();
System.out.println(person1.name);
System.out.println(person2.name);
System.out.println(person1.address.city);
System.out.println(person2.address.city);
System.out.println("-------------------------------------");
// Change the address of person2
person2.name = "Paul";
person2.address.city = "Mumbai";
System.out.println(person1.name);
System.out.println(person2.name);
System.out.println(person1.address.city);
System.out.println(person2.address.city);
}
}