java 浅拷贝和深拷贝 对象克隆clone

转载:https://www.cnblogs.com/xuanxufeng/p/6558330.html#top

class Professor0 implements Cloneable {
    String name;
    int age;
 
    Professor0(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Student0 implements Cloneable {
    String name;
    int age;
    Professor0 p; 
 
    Student0(String name, int age, Professor0 p) {
        this.name = name;
        this.age = age;
        this.p = p;
    }
 
    public Object clone() {
        Student0 o = null;
        try {
            o = (Student0) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e.toString());
        }
 
        return o;
    }
}

浅拷贝:

深拷贝:

猜你喜欢

转载自www.cnblogs.com/myseries/p/10152704.html