JAVA clone error: The method clone () from the type Object is not visible

The object is a copy of a cloning technique, called objects.
There is a summary of the Object class clone () method:
protected Onject clone () throws CloneNotSupportedException
class if an object wants to be all kinds of cloning, the object is located must implement the Cloneable interface.
This interface does not define any method, is a marker interface
Next we look at the specific code implementation:
The following is the correct code:

 

//要实现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 + "]";
	}
	
	// this method overrides on the line, nothing to write 
	@Override 
	protected Object clone () throws CloneNotSupportedException { 
	
		return super.clone (); 
	} 
---------------- 
Copyright : this article is CSDN blogger "Chen jiaoshou 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. 
Original link: https: //blog.csdn.net/weixin_43660039/article/details/84992348

  

The results show:

I am a native dog: Dog [name = tom, age = 3]
I was cloned dog: Dog [name = tom, age = 3]
1
2
Note that: modifier clone overridden method is protected, protected means, when cloning
master methods should override method clone in a package, or an error will be reported as follows:

Method, clone at The () from IS at The Object of the type not visible
----------------
Copyright: Original article is CSDN blogger "Chen jiaoshou", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/weixin_43660039/article/details/84992348

Guess you like

Origin www.cnblogs.com/max-hou/p/12003242.html