0

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.

TheGirl
  • 19
  • 3
  • 1
    Start by reading the documentation: https://docs.oracle.com/javase/10/docs/api/java/lang/Cloneable.html – Michael Jan 07 '20 at 12:56
  • 3
    *"Sorry if I sound stupid. I have just began learning Java."* - Java Lesson #2 - the Java class libraries are vast, but they are well documented. When you don't understand something about some standard class or method. The first thing you should do is lookup and read the javadocs for the class / method. Do this before asking on StackOverflow. It will save you time (and down votes ... for not doing your research. – Stephen C Jan 07 '20 at 13:08
  • 1
    @StephenC lessons are indeed never demotivating. But asking is very important part of learning lessons. People come here to learn and we learn by *ASKING*. – TheGirl Jan 08 '20 at 14:50

2 Answers2

2

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • But can we not override Object.clone() and add code to make a deep copy in the overiden version? should be fine. right? – TheGirl Jan 08 '20 at 14:29