Cloning objects in Java [3 questions]

后端 未结 3 1379
醉话见心
醉话见心 2021-01-29 02:04

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?

         


        
3条回答
  •  盖世英雄少女心
    2021-01-29 02:49

    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

提交回复
热议问题