Java浅克隆和深克隆深入理解(3)

public class CarCloneTest {
    public static void main(String[] args) {
        Brand brand = new Brand("BMW");
        Car car = new Car(5, brand);
        Car carClone;
//        carClone = (Car) car.clone();  //(1)
//        carClone = (Car) car.deepClone(); //(2)
        carClone = CloneUtil.deepClone(car);
       
        System.out.println("******************************************");
        System.out.println("car "+car);
        System.out.println("carClone "+carClone);
       
        System.out.println("******************************************");
        System.out.println("将car年限改为 7,品牌名称改为Banz");
        brand.setName("Banz");
        car.setYear(7);
       
        System.out.println("******************************************");
        System.out.println("car "+car);
        System.out.println("carClone "+carClone);
    }
}

运行测试程序,得到结果如下:

******************************************
car [year=5, brand=Brand [name=BMW]]
carClone [year=5, brand=Brand [name=BMW]]
******************************************
将car年限改为 7,品牌名称改为Banz
******************************************
car [year=7, brand=Brand [name=Banz]] carClone [year=5, brand=Brand [name=BMW]]

可见通过反序列化对象进行克隆也能得到我们想要的结果。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/63548b79216deb77b39a1480ebd33c9c.html