What is cloning? Explain how to design a class that supports cloning

What is cloning? Explain how to design a class that supports cloning.

If you create an object on the heap and assign the object to another object, then the compiler does not create another object. Only the reference of that object is assigned to the other.

Example:
A a = new A();
A b = new B();
Then b = a, will not create a new object for b. b will just be assigned the reference to the object.

In Java, there is no direct way to copy the contents of an object into a new object.

Thus to be able to copy the objects into another one, the clone method can be used.

While cloning, following things should be remembered:

1. Implement the Clonable interface.
2. Override implementation of the clone() method of the object class.
3. Make the clone method in your class public.
4. Your first statement in the clone method should be super.clone().

Example:
class A implements Cloneable
{
   ...
   public Object clone()
   {
       try
       {
           return super.clone();
       }
       catch( CloneNotSupportedException e )
       {
           System.out.println("CloneNotSupportedException");
       }
   }
       ...
}

Note: The default implementation of Object.clone only performs a shallow copy.
What are packages in java? Explain the purposes of packages
What are packages in java? - A package is a grouping of related types providing access protection and name space management...
What are access levels for classes and interfaces?
Access levels for classes and interfaces...
What is the List interface?
What is the List interface? - The List interface provides an ordered collection. Elements in the List can be accessed using integer indexes...
Post your comment
Discussion Board
java
can we create a concrete method
in interface ????????
pratap kumar sahu 07-3-2015