本篇文章参考自《Effective Java》第三版第十三条"Always override toString",在《阿里巴巴Java开发手册》中也有对clone方法规约:
【推荐】慎用 Object的 clone方法来拷贝对象。
说明:对象clone 方法默认是浅拷贝,若想实现深拷贝需覆写clone 方法实现域对象的深度遍历式拷贝。
关于深拷贝和浅拷贝的见解,还可以参考此文章:https://www.jianshu.com/p/94dbef2de298
实例通过调用clone()方法创建一份一模一样的拷贝,在这过程中没有调用构造方法
但是注意,拷贝有浅拷贝和深拷贝之分,在原文中并没有对浅拷贝和深拷贝的区别进行详细的区分
Cloneable接口内没有定义任何的方法,实现它仅仅是为了改变超类Object中受保护的clone()方法的行为,使得它能够真正做到field-for-field拷贝
A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
倘若我们在没有实现Cloneable接口的情况下重载clone()方法,则会在调用时抛出CloneNotSupportedException异常
Invoking Object‘s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
相反的,倘若我们仅仅只是实现Cloneable接口,而没有重载clone()方法,也无法做到实例的拷贝
Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
因此,我们要保证类既实现了Cloneable接口,也重载了clone()方法
By convention, classes that implement this interface should override Object.clone (which is protected) with a public method.
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
原文:https://www.cnblogs.com/kuluo/p/12875206.html