java——实现浅克隆(实际上是Object类的clone()方法)

1,实现浅克隆的步骤
(1):实现接口Cloneable(声明式接口,只有名字,没有抽象方法)
(2):重写object#clone()方法
[首先需要明白:object类的clone()方法类型是protected,(也就是说clone()只能在Object这个类中使用)返回值类型是object,定义一个类的时候要实现克隆就必须实现Cloneable接口,重写clone方法,引用的时候,注意类型转换]
例如
++++++++++++++++++++++++++++++++
public class Student implements Cloneable{
private String name;
private String gender;
private int age;
private String school;

public Student() {
}

public Student(String name, String gender, int age, String school) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.school = school;
}

@Override
public String toString() {
    return "Student{" +
            "name='" + name + '\'' +
            ", gender='" + gender + '\'' +
            ", age=" + age +
            ", school='" + school + '\'' +
            '}';
}

@Override
protected Object clone() throws CloneNotSupportedException {
    return super.clone();
}

}
+++++++++++++++++++++++++++++++
public class ObjectDemo {
public static void main(String[] args){
Student stu1=new Student(“jerry”,“male”,20,“轻工业”);
Student stu2=stu1;//两个对象指向了同一块内存空间
System.out.println(stu1);
System.out.println(stu2);
System.out.println(“stu1#hashCode=”+stu1.hashCode());
System.out.println(“stu2#hashCode=”+stu2.hashCode());
Student stu3=null;
try {
stu3=(Student) stu1.clone();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
System.out.println("==clone对象=");
System.out.println(stu3);
System.out.println(“stu3#hashCode=”+stu3.hashCode());
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42981168/article/details/88072297