Desert Ice
Desert Ice

Reputation: 4630

Purpose of cloning in Java

I was going through the "special" features of Java, and started reading up on Cloning.

So currently what I understand is Cloning can be used to get a identical copy of an object. To do this you implement the Cloneable interface and override the clone method of Object(Which is really weird IMO)

My questions is more towards the comparison between C++ and Java. Why exactly is a separate clone method required when we already have support for copy constructors. Was there a historical reason on why cloning was thought of as must have feature?

PS: I am not asking about the need to "clone" as in what is the need of cloning a object in Java, what I am asking is the need for Cloneable and the clone method, when Java already supports copy constructors.

Upvotes: 1

Views: 280

Answers (2)

MichaelCMS
MichaelCMS

Reputation: 4763

Clone is meant to provide a a separate instance of an object without destroying the cloned one. It's quite useful(it's a must) in prototype pattern.

Copy constructor is usually called in C++ when passing by value (you can do use it at construction time as well, but usually it's called when passing objects through the stack either as paremeters or returns). So often times the initial object gets out of scope.

You can eventually interchange these two if you really want to go at it, but in reality they serve different purposes, and having clarity when one should be used instead of another is very helpful.

Besides the disambiguation of the name, you need to think about polymorphism , where you want to clone the object from a base pointer.

Copy constructors will be called on the type of pointer, while clone (if virtual, like it should be) will be called on the most derived implementation.

Upvotes: 0

Călin
Călin

Reputation: 337

IMO you question has two parts.

What is the need for the Cloneable interface?

The Cloneable interface is also known as a marker interface, which means that it does not have any methods, its whole purpose is to tell you, the user of that class, that it implements the clone() method which is inherited from Object. This enables you to do a check before calling the clone() method:

Animal a = new Dog();
Animal b;
if (a instanceof Cloneable)
    b = a.clone();

This happens pretty often in Java; see for example the Serializable interface.

Why does Java need a clone() method at all, as it already has copy constructors?

The very short answer is polymorphism. How would you correctly clone a Dog instance, through a reference to an Animal, its super class, if you didn't have the clone() method?

Upvotes: 1

Related Questions