Clone

The default clone () . is a shallow copy .

To be able to use clone().We must first implement the interface Clonnable.

Object.clone() : It’s inherited by every class automatically

Clone : means the creation of exact copy of an object. Creating a new instance of the class current object and initializes all of its field with exactly the contents of the corresponding fields of this object

The difference between shallow copy and deep copy is that. Shallow copy of an object will have the exact copy of all fields of original object. The deep copy will have all fields of original object just like shallow. However , if original object has any references to other objects as fields, then copy of those objects are also created.

Remember to include implements Cloneable interface in order to be able to clone your objects

  • Thrown to indicate that the clone object has been called to clone an object. But that it does not implement the Clonnable interface . 

Why are we returning Super.Clone , and not This.Clone ???

It servers two purposes : 

  • Make clone() public (Object.clone() is protected)
  • Handle cases where a subclass doesn’t implement Clonnable. 

Let’s create two objects realmadrid , and Juventus .

Our goal is to have the same soccer player with the same jersey number for both teams .

Output from main :

Awesome we cloned both objects to return the same output , great !

Leave a comment