回忆:之前听一个老师提过,学语言就是学关键字,如果把所有的关键字都搞懂了,这门语言你就属于很熟悉了(很赞同这句话)。
实现Cloneable这个标记接口,重写Object的clone方法,完成拷贝功能
拷贝分为浅拷贝和深拷贝
如果拷贝的对象中的属性都是基本类型,使用浅拷贝就行,如果拷贝的对象中含有引用类型,就需要实现深拷贝
注意:实现深拷贝时,引用对象也要重写clone方法,如果引用对象是继承其他对象的话,上级对象也要重写clone方法。
对象
package com.example.java8.model.copy;
import java.math.BigDecimal;
public class Dog implements Cloneable {
private Integer id;
private String name;
private BigDecimal weight;
private Food food;
public Dog(Integer id, String name, BigDecimal weight) {
this.id = id;
this.name = name;
this.weight = weight;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getWeight() {
return weight;
}
public void setWeight(BigDecimal weight) {
this.weight = weight;
}
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
@Override
public String toString() {
return "Dog{" +
"id=" + id +
", name='" + name + '\'' +
", weight=" + weight +
", food=" + food +
'}';
}
// 浅拷贝(使用时两者选其一)
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
// 深拷贝(使用时两者选其一)
@Override
protected Object clone() throws CloneNotSupportedException {
Object object = super.clone();
Food food = ((Dog) object).getFood();
((Dog) object).setFood((Food) food.clone());
return object;
}
}
引用对象
package com.example.java8.model.copy;
public class Food implements Cloneable {
private String name;
public Food(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试方法
package com.example.java8.model.copy;
import org.junit.Test;
import java.math.BigDecimal;
public class DogTest {
// 测试浅拷贝
@Test
public void test() throws CloneNotSupportedException {
Dog jack = new Dog(18, "jack", BigDecimal.TEN);
Dog tom = (Dog) jack.clone();
tom.setId(19);
tom.setName("tom");
tom.setWeight(BigDecimal.ONE);
System.out.println(jack);
System.out.println(tom);
}
// 测试深拷贝
@Test
public void test2() throws CloneNotSupportedException {
Dog jack = new Dog(18, "jack", BigDecimal.TEN);
jack.setFood(new Food("冰淇淋"));
Dog tom = (Dog) jack.clone();
tom.setId(19);
tom.setName("tom");
tom.setWeight(BigDecimal.ONE);
tom.getFood().setName("三明治");
System.out.println(jack);
System.out.println(tom);
}
}