將一個對象復制一份,稱為對象的克隆技術。
在Object類匯總存在一個clone()方法:
protected Onject clone() throws CloneNotSupportedException
如果某各類的對象想被克隆,則對象所在的類必須實現Cloneable接口。
此接口沒有定義任何方法,是一個標記接口
接下來我們看看具體代碼實現:
以下是正確的代碼:
//要實現Cloneable這個接口,不用傳參 public class Dog implements Cloneable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Dog() {} public Dog(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Dog [name=" + name + ", age=" + age + "]"; } //把這個方法重寫一下就行,什么都不寫 @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } ———————————————— 版權聲明:本文為CSDN博主「陳jiaoshou」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/weixin_43660039/article/details/84992348
結果展示:
我是原生dog:Dog [name=tom, age=3]
我是克隆dog:Dog [name=tom, age=3]
1
2
需要注意的是:clone重寫的方法的修飾詞是protected,受保護的意思,此時克隆的
主方法應該和重寫clone的方法在一個包中,否則會報如下錯誤:
The method clone() from the type Object is not visible
————————————————
版權聲明:本文為CSDN博主「陳jiaoshou」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43660039/article/details/84992348