Java克隆和克隆方法工作

时间:2018-04-19 03:54:43

标签: java object deep-copy cloning notsupportedexception

我是java的新手,我试图弄清楚在我的搜索操作中克隆是如何工作的我偶然发现了深度克隆的程序代码,但我不知道这个程序是写还是错了所以请帮助我..这是代码...

我的问题是,我们可以实现这个受保护的对象clone()在两个不同的类中抛出CloneNotSupportedException吗?如果是,那么我们为什么要这样做?请尽可能简单地回答......提前致谢...

PS:这是我的第一个问题。所以请耐心等待....

class A implements Cloneable
{
    int i;

    public A(int i)
    {
        this.i = i;
    }

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

class B implements Cloneable
{
    int j;

    A a;

    public B(int j, A a)
    {
        this.j = j;

        this.a = a;
    }

        //Overriding clone method to implement deep copy

    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        B b = (B) super.clone();

        b.a = (A) a.clone();

        return b;
    }
}

public class CloneMethodDemo
{
   public static void main(String[] args)
   {
       A a = new A(10);

       B b1 = new B(20, a);

       B b2 = null;

       try
       {
           //Creating clone of b1 and assigning it to b2

            b2 = (B) b1.clone();
       }
       catch (CloneNotSupportedException e)
       {
           System.out.println("Onject is not clone-able");
       }

       //Printing value of b1.a.i

       System.out.println(b1.a.i);        //Output : 10

       //Changing the value of b2.a.i to 100

       b2.a.i = 100;

       //Now, this change will not effect the original object

       System.out.println(b1.a.i);         //Output : 10
   }
}

0 个答案:

没有答案