Java Clone method

To clone something is to make a duplicate of it.The clone() method in Java makes an exact duplicate of an object .

Why would someone need cloneing ?
Java’s method calling semantics are call-by-refrence , which allows the called method to modify the state of an object that is passed into it . Cloning the input object before calling the method would pass a copy of the object keeping orignal safe.

Cloneing is not enabled by default in classes that you write.Clone method is a protected method , which means that your code cannot simply call it .Only the class defining can clone it’s objects.

Foo f = new Foo();
Foo f2 = new f.clone();

If you try clone() without any special prepration as in code written above you will encouter errors.

How to clone?
You must do two things to make your class cloneable:

  • Override Object’s Clone method
  • Implement the empty Cloneable interface

Example :

public class FooClone impements Cloneable{

public FooObject clone() throws CloneNotSupportedException

( return super.clone();

)

// more code

Advertisements