Search code examples
javaclassabstract-classclone

Cloning objects in Java [3 questions]


will the clone method of Asub be called by doing this? Or is Asub deep cloned properly? If not, is there a way to propery deep clone Asub through this kind of method?

abstract class Top extends TopMost {
    protected Object clone() {
        Object obj = super.clone();
        // deep copy and try catch
    }


}

abstract class A extends Top { 
    protected Object clone() {
        Object obj = super.clone();
       // deep copy and try catch
    } 


}

class Asub extends A {
    protected Object clone() {
        Object obj = super.clone();
        // deep copy and try catch
    }

    public void doSomethingNew() {
    }
}

abstract class TopMost {
    public void someMethod() {
        Top a = (Top) super.clone();
        // more code here
    }
}

public class Main {
    public static void main(String... args) {
        Asub class1 = new Asub();
        class1.someMethod();
    }
}

Solution

  • By allowing all abstract subclasses implementing super.clone() essentially does nothing (since all your abstract classes in your example are doing nothing) and just call (at the end) Object.clone() method.

    My suggestion is to allow all concrete classes (like ASub) to override the clone method and use the copy constructor idiom to create an exact clone of itself....

    e.g.

    public abstract class TopMost {
    
        public TopMost(TopMost rhs) {
    
        }
    
    }
    
    public abstract class Top extends TopMost {
    
        public Top(Top rhs) {
            super(rhs);
    
            //whatever you need from rhs that only is visible from top
        }
    }
    
    public abstract class A extends Top { 
    
        public A (A rhs) {
            super(rhs);
    
            //TODO: do rhs copy
        }
    }
    
    public class ASub extends A {
    
        public ASub(ASub rhs) {
            super(rhs);
    
            //TODO: copy other stuff here....
        }
    
        public Object clone() {
            return new ASub(this);
        }
    }
    

    PS Make TopMost Cloneable