definition
A copy of an object, the object of cloning technology known as
the existence of a clone in class Object () method:
protected Object clone () throws CloneNotSupportedException
class if the object of a class want to be cloned, the object resides must implement Cloneable interface. This interface does not define any method, is a marker interface
step
1, the interface implemented Clonrable
2, override the clone method of the Object class
Examples
Description: create the copied object class that implements Clonrable interface and override the clone method in class Object
//实现Clonrable接口
public class Cat implements Cloneable {
private String name;
private int age;
public Cat(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Cat() {
super();
// TODO Auto-generated constructor stub
}
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;
}
@Override
public String toString() {
return "Cat [name=" + name + ", age=" + age + "]";
}
//重写Object中的clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
Description: create an object that implements copy the class
public class Test {
public static void main(String[]args) {
Cat cat=new Cat("喵喵小白",2);
try {
Cat newCat=(Cat)cat.clone();
System.out.println("cat"+cat);
System.out.println("newCat"+newCat);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Run Results:
catcat [name = Meow white, age = 2]
newCatCat [name = Meow white, age = 2]