回憶:之前聽一個老師提過侠畔,學(xué)語言就是學(xué)關(guān)鍵字,如果把所有的關(guān)鍵字都搞懂了损晤,這門語言你就屬于很熟悉了(很贊同這句話)软棺。
實現(xiàn)Cloneable這個標(biāo)記接口,重寫Object的clone方法尤勋,完成拷貝功能
拷貝分為淺拷貝和深拷貝
如果拷貝的對象中的屬性都是基本類型喘落,使用淺拷貝就行,如果拷貝的對象中含有引用類型最冰,就需要實現(xiàn)深拷貝
注意:實現(xiàn)深拷貝時瘦棋,引用對象也要重寫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);
}
}