浅拷贝介绍:
(1)对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象
(2)对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象.因为在实际上两个对象的成员变量都指向同一个实例.在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值.
(3)前面我们克隆羊就是浅拷贝
(4)浅拷贝是使用默认的clone()方法来实现:sheep = (Sheep) super.clone();
下面我们来看下有关浅拷贝的代码:
public class Client {
public static void main(String[] args) {
Sheep sheep = new Sheep("tom",1,"白色");
sheep.friend = new Sheep("jack",2,"黑色");
Sheep sheep2 = (Sheep)sheep.clone();//克隆
Sheep sheep3 = (Sheep)sheep.clone();//克隆
Sheep sheep4 = (Sheep)sheep.clone();//克隆
Sheep sheep5 = (Sheep)sheep.clone();//克隆
System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
System.out.println("sheep3 =" + sheep3 + "sheep3.friend=" + sheep3.friend.hashCode());
System.out.println("sheep4 =" + sheep4 + "sheep4.friend=" + sheep4.friend.hashCode());
System.out.println("sheep5 =" + sheep5 + "sheep5.friend=" + sheep5.friend.hashCode());
}
}
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
public String address = "蒙古羊";
public Sheep friend ; //对象,克隆如何处理对象
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String nam