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

猜你喜欢

转载自www.cnblogs.com/max-hou/p/12003242.html
今日推荐