MY mENU


Tuesday 20 March 2012

Cloning In Java


Cloning:  Cloning means creating duplicate copy with current object state is called cloning.

Requirement: If we create objects with new keyword and constructor always objects are created with default initial state. If we want to create second object with first object current modified state, we must used cloning.

For Example  consider below example;:
Consider a bikes manufacturing factory, here all bikes has same state except few properties like engine number, model number etc.
          To develop this factory application it is recommended to use cloning approach. because once we create object, in all other objects we need to change only the specific properties.

        To perform cloning we must use Object's class clone Method.

Rule:
       To clone an object, its class must be subclass of java.lang.Cloneable interface. It is a marker interface. It means only Cloneable objects are cloned by JVM . If object is not of type Cloneable  JVM throws exception java.lang.CloneNotSupprotedEception. Below application shows performing cloning.

//Factory.java
class Bike implements Cloneable{
int bikeNumber;
int engineNumber;
int modelNumber;
String type;

Bike(int bikeNumber; int engineNumber; int modelNumber; String type;){
     this.engineNumber=engineNumber;
         this.modelNumber=modelNumber;     
         this.type=type;
}
public Object clone() throws CloneNotSupportedException
{
    //current bike object is cloned
    Bike b1=(Bike)super.clone();

//changing individual property
  b1.engineNumber=  b1.engineNumber+10;

//returning cloned bike
return b1;
}}
class factory
public static void main(String[] args) throws CloneNotSupportedException{
       Bike b1= new Bike(4221,5673,"Pulsar 180cc");
     
        //cloning first bike object
    Bike b2=(Bike)b1.clone();

//clone method create new object , so == returns false
  System.out.println(b1==b2);

     System.out.println("b1 object state");
      System.out.println("b1.engineNumber:"+b1.engineNumber);
           System.out.println("b1.modelNumber:"+b1.modelNumber);
                   System.out.println("b1.type:"+b1.type);

 System.out.println();
     System.out.println("b2 object state");
      System.out.println("b2.engineNumber:"+b2.engineNumber);
           System.out.println("b2.modelNumber:"+b2.modelNumber);
                   System.out.println("b2.type:"+b2.type);
}}

No comments:

Post a Comment