今天打了复制的代码
主要点就是实现Cloneable接口并重写代码。
关于深层和浅层代码的复制可以这样理解
比喻:一个人穿了三件衣服,另外一个人也想穿和他一样的外套,这就是浅层复制。
如果想和他穿一模一样的三件衣服时,就是深层复制。
代码实现:先建一个属性类
public class Food implements Cloneable{
public Chicken chicken;
public String pork;
public int breed;
public Food() {
super();
// TODO Auto-generated constructor stub
}
public Chicken getChicken() {
return chicken;
}
public void setChicken(Chicken chicken) {
this.chicken = chicken;
}
public String getPork() {
return pork;
}
public void setPork(String pork) {
this.pork = pork;
}
public int getBreed() {
return breed;
}
public void setBreed(int breed) {
this.breed = breed;
}
/**
* 重写复制的方法
*/
@Override
protected Object clone() throws CloneNotSupportedException {
//获取实例对象
Food food=new Food();
//设置深层复制的关键
food=(Food) super.clone();
food.setChicken(new Chicken(this.getChicken().getChickenWing(),
this.getChicken().getDrumstick(),this.getChicken().getAmount()));
return food;
}
@Override
public String toString() {
return "Food [chicken=" + chicken + ", pork=" + pork + ", breed=" + breed + "]";
}
}
在建别一个属性类(该属性是上一个属性类的属性)
public class Chicken implements Cloneable{
public String drumstick;
public String chickenWing;
public int amount;
public Chicken() {
super();
}
public Chicken(String drumstick, String chickenWing, int amount) {
super();
this.drumstick = drumstick;
this.chickenWing = chickenWing;
this.amount = amount;
}
public String getDrumstick() {
return drumstick;
}
public void setDrumstick(String drumstick) {
this.drumstick = drumstick;
}
public String getChickenWing() {
return chickenWing;
}
public void setChickenWing(String chickenWing) {
this.chickenWing = chickenWing;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
/**
* 重写复制的方法
*/
@Override
protected Object clone() throws CloneNotSupportedException {
//复制当前的对象
Chicken chicken=(Chicken) super.clone();
return chicken;
}
@Override
public String toString() {
return "Chicken [drumstick=" + drumstick + ", chickenWing=" + chickenWing + ", amount=" + amount + "]";
}
}
一个测试类,用于测试时否有复制一个对象出来是否,可以了解复制出来的对象和原本的对象时分离的互不干扰
public class Text {
public static void main(String[] args) {
Food food=new Food();
Chicken chicken=new Chicken();
food.setBreed(1);
food.setPork("猪肉");
food.setChicken(chicken);
chicken.setChickenWing("鸡翅");
chicken.setDrumstick("鸡腿");
chicken.setAmount(100);
//把food原始数据付给f2
Food f2=food;
try {
//这里是复制一个对象实例到fo3去
Food fo3=(Food) food.clone();
fo3.setBreed(5);
//把品类改成3
fo3.getChicken().setAmount(200);
//把鸡肉里面的数量改成200
fo3.getChicken().setDrumstick("大鸡腿肉");
System.out.println("原始数据1:"+food);
System.out.println("原始数据2:"+f2);
System.out.println("取得复制的数据:"+fo3);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
总结:
深层复制就是以实现Cloneable接口为重点,重写为主要。
以super.close()方法和其要复制的属性为侧重点。