Java对象克隆(复制):深复制和浅复制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangmingbao2016/article/details/73477137

java中,对象的赋值(我感觉是实例化,可能说法不准确)一般有三种方式(以Student类为例):
第一:Student student = new Student;(new 一个对象实例,最常用)
第二:Student student2 = student;(即将一个已存在的对象的地址复制给一个新对象,强调一下)
第三:Student student3 = student.clone();(将一个已经存在的对象的值复制给一个新对象,包括深复制和浅复制,下面将介绍)
首先,我们来看一个例子:

Student.java:
public class Student implements Cloneable {
    int age;

    @Override
    public Object clone() {
        Student cloobj = null;
        try {
            cloobj = (Student) super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cloobj;
    }
}



TestMain.java:
public class TestMain {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student st = new Student();
        st.age = 100;
        Student st1 = st;
        Student st2 = (Student) st.clone();
        System.out.println(st.age);
        System.out.println(st1.age);
        System.out.println(st2.age);
        System.out.println(i);
        System.out.println(j);
        System.out.println("***************************************");
        st.age = 10;
        System.out.println(st.age);
        System.out.println(st1.age);
        System.out.println(st2.age);
        System.out.println("***************************************");
        st1.age = 200;
        System.out.println(st.age);
        System.out.println(st1.age);
        System.out.println(st2.age);
        System.out.println("***************************************");
        st2.age = 300;
        System.out.println(st.age);
        System.out.println(st1.age);
        System.out.println(st2.age);
        System.out.println("***************************************");

    }
}

运行以上程序,输出如下:

100
100
100
1
1
***************************************
10
10
100
2
1
***************************************
200
200
100
2
3
***************************************
200
200
300
***************************************

由结果可以得出结论:
通过“=”进行对象实例化的其实是地址传递,即st和st1真正指向的是同一个地址,改变st的属性值会影响st1,改变st1的属性值也会影响st,但是,无论是修改st还是st1,都不会影响st2的值,修改st2的属性值也不会影响st和st1,这说明st2指向了另一个地址区域,有过C语言基础的人都知道,C语言中有传值和传地址的区分。
未完。。。。待续

猜你喜欢

转载自blog.csdn.net/zhangmingbao2016/article/details/73477137