Can clone object creation method using constructor

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

But while reading Effective Java Point 11: Redefining the clone intelligently , I found an expression that says that

The provision that "constructors are not called" is too large. the good clone behavior method can call constructors to create objects inside the clone under construction. If the class is final, the clone may even return an object created by the constructor.

Can someone explain this to me?

+7
java clone
source share
1 answer

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

The implementation in Object.clone() does not call the constructor.

There is nothing that would prevent you from realizing it yourself in this way. For example, this is a valid implementation of clone() :

 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 do this (of course) if the class is final , because then you can guarantee the return of an object of the same type as the original.

If the class is not final, I think you could check if the instance was β€œjust” an instance of type overriding clone() and handle it differently in different cases ... it would be weird to do it though.

+12
source share

All Articles