Person类中,实现implements Cloneable接口
@Override
重写clone()这个父类方法后,还需要把protected改为public,
类型是当前重写的子类类型才能正常使用
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public class boy {
String name;
int age;
//get、set、有参无参构造、toString方法
}
public class Person implements Cloneable{
String name;
String sex;
int age;
boy boy;
}
public class Test2 {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person();
p1.setName("李白");
p1.setSex("女");
p1.setAge(18);
Person p2 = p1.clone();
System.out.println(p1+"===="+p1.hashCode());
System.out.println(p2+"===="+p2.hashCode());
boy b = new boy();
b.setName("小孩");
b.setAge(3);
p1.setBoy(b);
Person p3 = p1.clone();
System.out.println(p1+"========"+p1.hashCode()+"====="+p1.getBoy().hashCode());
System.out.println(p1+"========"+p3.hashCode()+"======="+p1.getBoy().hashCode());
}
}