欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 深拷贝实现 重写Object的clone方法

程序员文章站 2022-05-20 09:40:30
...
public class Test02 {
    public static void main(String[] args) {
        Student student = new Student("238");
        try {
            Student student1 = student.clone();
            System.out.println(student.getName());
            System.out.println(student1.getName());
            System.out.println("是否一样" + (student == student1 ? true : false));

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

//实现Cloneable,不写会抛异常
class Student implements Cloneable {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

	//方法公开
    @Override
    public Student clone() throws CloneNotSupportedException {
        return (Student) super.clone();
    }

}
相关标签: java object