deep copy, swallow copy

This commit is contained in:
kim
2021-01-11 18:39:34 +09:00
parent 12d96fec9e
commit f52780c38e
3 changed files with 78 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
package Prototype.copy;
public class Age {
private int year;
private int value;
public Age(int year, int value) {
this.year = year;
this.value = value;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

View File

@@ -0,0 +1,29 @@
package Prototype.copy;
public class Cat implements Cloneable{
private String name;
private Age age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Age getAge() {
return age;
}
public void setAge(Age age) {
this.age = age;
}
public Cat copy() throws CloneNotSupportedException {
Cat cat = (Cat) this.clone();
cat.setAge(new Age(this.age.getYear(), this.age.getValue()));
return cat;
}
}

View File

@@ -0,0 +1,21 @@
package Prototype.copy;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Cat navi = new Cat();
navi.setName("navi");
navi.setAge(new Age(2018, 3));
Cat tom = navi.copy();
tom.setName("tom");
tom.getAge().setYear(2020);
tom.getAge().setValue(1);
System.out.println(navi.getName());
System.out.println(navi.getAge().getYear());
System.out.println(tom.getName());
System.out.println(tom.getAge().getYear());
}
}