javacloneable

Delegation of clone() method call in inheritance in java


1.Child class extends Parent class. 2.Child class implements Cloneable and overrides clone() method calls super.clone() 3.Parent class doesn't implement Cloneable interface neither it overrides clone() method.

Output: Both parent and child class state's are cloned.

Question: How Parent class state is cloned by Object class when Parent class has not implemented marker interface Cloneable?

class ParentCloneableClass{
    String val;
    public ParentCloneableClass(String val){
        this.val = val;
    }

    public String getVal() {
        return val;
    }
}
class CloneableClass extends ParentCloneableClass implements Cloneable{
    String name;
    public CloneableClass(String name){
        super("parentClass");
        this.name = name;
    }

    @Override
    public   CloneableClass clone() throws CloneNotSupportedException {
        return (CloneableClass) super.clone();
    }

    public String getName() {
        return name;
    }
}

class Demo{
   public static void main(String[] args) throws CloneNotSupportedException {
        CloneableClass cloneableClass = new CloneableClass("deepak");
        CloneableClass cloneableClassCloned = cloneableClass.clone();
   }
}

Solution

  • The class Object checks the runtime type of the object being cloned, not the compile time type. So the object at runtime is of type Cloneable which does implements Cloneable, hence the Object class performs the cloning accordingly:

    The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown... Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.