比如:别人有一个漂亮的车C1
浅拷贝:复制一个C1的钥匙,但是如果C1内部改变(车身变色),再去使用C1就会发现它变了。
深拷贝:按照C1自己搭建一个一模一样的C2,如果C1发生改变不会影响C2,C2的改变也不会影响C1。
## java代码
定义一个Car类,实例化两个对象c1和c2,令c2=c1,在输出结果中,如果c1改变c2也随之变化,同时c1和c2指向同一地址
```java
Car c1 = new Car("BWM",001);
Car c2= new Car("MMM",001);
//Car c2 = c1.clone(); //深拷贝
c2 = c1; //浅拷贝
c1.setName("Benz");//更改c1 的name
System.out.println("parent1 = " + c1.toString());
System.out.println("parent2 = " + c2.toString());
System.out.println(System.identityHashCode("c1指向的地址"+c1));
System.out.println(System.identityHashCode("c2指向的地址"+c2));
```
运行结果:c2的值随c1值变化
```java
parent1 = Car[Benz===1]
parent2 = Car[Benz===1]
c1指向的地址:408904361
c2指向的地址:408904361
```
使用深拷贝clone方法:
```java
@Override
protected Car clone(){
Car clone = null;
try{
clone = (Car)super.clone();
}catch (CloneNotSupportedException e){
throw new RuntimeException(e);
}
return clone;
}
```
主函数中更改克隆方式
```java
Car c1 = new Car("BWM",001);
//Car c2= new Car("MMM",001);
Car c2 = c1.clone(); //深拷贝
//c2 = c1; //浅拷贝
c1.setName("Benz");//更改c1 的name
System.out.println("parent1 = " + c1.toString());
System.out.println("parent2 = " + c2.toString());
```
运行结果:c2的值不随c1的值变化
```java
parent1 = Car[Benz===1]
parent2 = Car[BWM===1]
c1指向的地址:1628257689
c2指向的地址:742865302
```
全部代码:
```java
public class Main {
public static void main(String[] args)
{
Car c1 = new Car("BWM",001);
//Car c2= new Car("MMM",001);
Car c2 = c1.clone(); //深拷贝
//c2 = c1; //浅拷贝
c1.setName("Benz");//更改c1 的name
System.out.println("parent1 = " + c1.toString());
System.out.println("parent2 = " + c2.toString());
System.out.print("c1指向的地址:");
System.out.println(System.identityHashCode(c1));
System.out.print("c2指向的地址:");
System.out.println(System.identityHashCode(c2));
}
public static class Car implements Cloneable{
String name = "";
int num=0;
Car(String n,int num)
{
this.name = n;
this.num = num;
}
public void setName(String na){
name = na;
}
public void setNum(int n){
num = n;
}
@Override
protected Car clone(){
Car clone = null;
try{
clone = (Car)super.clone();
}catch (CloneNotSupportedException e){
throw new RuntimeException(e);
}
return clone;
}
public String toString(){
return "Car["+name+"==="+num+"]";
}}}