JAVA克隆對象報錯:The method clone() from the type Object is not visible


將一個對象復制一份,稱為對象的克隆技術。
在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM