package test;
public class ClassTest implements Cloneable{
public String name;
public int age;
public ClassTest(String name,int age) {
this.setName(name);
this.setAge(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;
}
@Override
public String toString() {
System.out.println(this.getName() + ";" + this.getAge());
return "";
}
/**
* 若想在其它类中也能够克隆该类,必须实现该方法
* 若不实现,克隆只能在该类中使用
* 如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。
* 按照惯例,实现此接口的类应该使用公共方法重写 Object.clone(它是受保护的)。
*/
public ClassTest Clone() throws Exception{
return (ClassTest)this.clone();
}
public static void main(String[] args) throws Exception{
ClassTest c = new ClassTest("zhang", 23);
ClassTest c2 = (ClassTest)c.clone();
c2.setName("quan");
System.out.println(c);
System.out.println(c2);
}
}
public class ClassTest implements Cloneable{
public String name;
public int age;
public ClassTest(String name,int age) {
this.setName(name);
this.setAge(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;
}
@Override
public String toString() {
System.out.println(this.getName() + ";" + this.getAge());
return "";
}
/**
* 若想在其它类中也能够克隆该类,必须实现该方法
* 若不实现,克隆只能在该类中使用
* 如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。
* 按照惯例,实现此接口的类应该使用公共方法重写 Object.clone(它是受保护的)。
*/
public ClassTest Clone() throws Exception{
return (ClassTest)this.clone();
}
public static void main(String[] args) throws Exception{
ClassTest c = new ClassTest("zhang", 23);
ClassTest c2 = (ClassTest)c.clone();
c2.setName("quan");
System.out.println(c);
System.out.println(c2);
}
}