0

我是 java 新手,我试图弄清楚在搜索操作期间如何在 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
   }
}
4

0 回答 0