参考:https://blog.csdn.net/jeffleo/article/details/76737560
Student类:
package day13.Demo;
public class Student implements Cloneable{
private String name;
private int age;
private Cost cost;
public Student(){
}
public Student(String name, int age, Cost cost) {
super();
this.name = name;
this.age = age;
this.cost = cost;
}
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 Cost getCost() {
return cost;
}
public void setCost(Cost cost) {
this.cost = cost;
}
public Student clone() throws CloneNotSupportedException {
Student cloned = (Student) super.clone();
cloned.cost = (Cost) cost.clone(); //这一步添上去说明是深克隆
//这一步省略说明是浅克隆
return cloned;
}
@Override
public String toString() {
System.out.println("[name:" + this.getName()+ " age:" + this.getAge()
+ " cost:" +this.getCost().getMoney()+"]");
return "";
}
}
Cost类:
package day13.Demo;
public class Cost implements Cloneable, Comparable<Cost>{
private int money;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
测试类TestClone:
package day13;
import java.util.Arrays;
import day13.Demo.Cost;
import day13.Demo.Student;
public class TestClone {
public static void main(String[] args) throws
CloneNotSupportedException {
Cost cost = new Cost();
cost.setMoney(1000);
Student stu = new Student("徐子峰", 20, cost);
//stu对象中基本数据类型的hashcode值
System.out.println(stu.hashCode());
//stu对象中引用类型Cost的hashcode值
System.out.println(stu.getCost().hashCode());
System.out.println(stu.toString());
//测试浅克隆后,stu对象中改变引用类型Cost中的值会引起的变化
cost.setMoney(2000);
Student stu1 = (Student)stu.clone();
//stu对象中基本数据类型克隆后的hashcode值
System.out.println(stu1.hashCode());
//stu对象中引用类型Cost克隆后的hashcode值
System.out.println(stu1.getCost().hashCode());
System.out.println(stu1.toString());
System.out.println(stu.toString());
}
}