1 Reply Latest reply: Mar 30, 2013 9:50 PM by EJP RSS

    Help with clone method

    956015
      Hi,

      I'm having some trouble understanding cloning when it comes to subclasses.

      This is my code:
      class Base implements Cloneable
      {
           int x;
           
           public Base clone() throws CloneNotSupportedException
           {
                Base cloned = (Base) super.clone();
                return cloned;
           }
           
      }
      class Derived extends Base
      {
           int y = 1;
           
           public Derived clone() throws CloneNotSupportedException
           {
                Derived cloned = (Derived) super.clone();
                return cloned;
           }
      }
      I believe that this works but I don't quite understand how a clone of Derived is made. To my understanding the super call to clone in the Base class is a call to Object's clone method. When clone is called on an instance of Derived, we go to the clone method in Derived which calls the clone method in Base. Then we go the clone method in Base which calls Object's clone method on an instance of Derived? Object's clone method copies both fields of the Base class and Derived class and returns an Object that's holding a derived?

      I guess my confusion is from the super call. Can I get some clarification?

      Thank you.

      Edited by: 953012 on Mar 30, 2013 7:25 PM
        • 1. Re: Help with clone method
          EJP
          The close method in Base which calls Object's clone method on an instance of Derived?
          Yes.
          Object's clone method copies both fields of the Base class and Derived class and returns an Object that's holding a derived?
          It returns a Derived with all the same values in its fields and its super class's fields.