Java cloning abstract objects

后端 未结 4 1046
执笔经年
执笔经年 2020-12-16 15:37

I\'m wondering if there is any way to do the following. I have an abstract class, Shape, and all its different subclasses and I want to override the clone metho

4条回答
  •  孤街浪徒
    2020-12-16 16:11

    You can't create deep clone of abstract class because they can't be instantiated. All you can do is shallow cloning by using Object.clone() or returning this

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

    or

    @Override
    public Object clone() throws CloneNotSupportedException {
        return this;
    }
    

    An abstract class can act as a reference, and it cannot have an instance so shallow cloning works in this case

    OR

    As a better approach, you can declare clone() as abstract and ask child class to define it, something like this

    abstract class Shape {
    
        private String str;
    
        public Shape(String str) {
            this.str = str;
        }
    
        public abstract Shape clone();
    
        public String toString() {
            return str;
        }
    }
    
    class Circle extends Shape {
    
        public Circle(String str) {
            super(str);
        }
    
        @Override
        public Shape clone() {
            return new Circle("circle");
        }
    
    }
    

提交回复
热议问题