TheGirl
TheGirl

Reputation: 19

confusion regarding clone() , Object class and Clonable Interface in Java

If clone() is a part of the Object class , then why do we need to implement Clonable interface to use clone()?

I have read that clone() is protected member of Object, then what is the relationship between clone() and Clonable interface. Sorry if I sound stupid. I have just began learning Java.

Upvotes: 0

Views: 122

Answers (2)

Joker
Joker

Reputation: 11156

It is highly not recommended to use clone(). I won't go into depth as this off topic but if you need more data on this please check Effective Java. Read Item 11: "Override clone judiciously".

Object.clone() has an implementation. It makes a shallow copy of the object if the object implements Cloneable.

The .clone() method does not belongs to any interface.

Having a .clone() method and implementing the Cloneable interface are completely different things.

You only need to implement the Cloneable interface if you intend to make use of Object's clone method

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Cloneable is a marker interface. It doesn't have any methods. Just to whitelist your class to make Cloneable

From docs

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

Upvotes: 2

Related Questions