Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can clone method create object using constructor

Tags:

java

clone

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

But, while reading Effective Java Item 11: Override clone judiciously, I found a statement which says that

The provision that “no constructors are called” is too strong. A well-behaved clone method can call constructors to create objects internal to the clone under construction. If the class is final, clone can even return an object created by a constructor.

Can someone please explain this to me?

like image 786
Anand Avatar asked Jul 31 '13 07:07

Anand


People also ask

Does clone method create new object?

In simple words, cloning is about creating a copy of the original object. Its dictionary meaning is: “make an identical copy of”. By default, Java cloning is 'field by field copy' because the Object class does not have any idea about the structure of the class on which the clone() method will be invoked.

Does clone call constructor?

The clone() method doesn't call any constructor so there will be no control on object creation. We need to implement the clone() method in a class whose object has to be cloned, we also need to handle CloneNotSupportedException and calling of the clone() method.


1 Answers

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.

like image 193
Jon Skeet Avatar answered Oct 24 '22 09:10

Jon Skeet