Can clone method create object using constructor

前端 未结 2 1970
别跟我提以往
别跟我提以往 2021-01-02 10:49

I always thought that clone() creates an object without calling a constructor.

But, while reading Effective Java Item 11: Override clone judicio

相关标签:
2条回答
  • 2021-01-02 11:41

    I think below part of code always create the new object and supply to the other class (i.e. helpfull in singleton).

     @Override
        public Object clone() {
            return new Foo(bar);
        }
    

    I think this can be supply for the purpose:

    public MyObject clone() {
        return new MyObject(this);
    }
    
    0 讨论(0)
  • 2021-01-02 11:42

    I always thought that clone() creates an object without calling a constructor.

    The implementation in Object.clone() doesn't call a constructor.

    There's nothing to stop you from implementing it yourself in a way which does. For example, this is a perfectly valid clone() implementation:

    public final class Foo implements Cloneable {
        private final int bar;
    
        public Foo(int bar) {
            this.bar = bar;
        }
    
        @Override
        public Object clone() {
            return new Foo(bar);
        }
    }
    

    You can only do this (unconditionally) if the class is final, because then you can guarantee to be returning an object of the same type as the original.

    If the class isn't final, I guess you could check whether the instance was "just" an instance of the type overriding clone() and handle it differently in different cases... it would be odd to do so though.

    0 讨论(0)
提交回复
热议问题