Search Java Programs

Wednesday, February 10, 2010

cloneable in Java

In this tutorial we are going to see use of cloneable interface and how to use it. The cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object to be made. If you try to call clone() on a class that does not implement Cloneable, a CloneNotSupportedException is thrown. When a clone is made the constructor for the object being cloned is not called. A clone is a copy of the original.

class Customer implements Cloneable 
{
String name;
int income;
public Customer(String name, int income)
{
this.name = name;
this.income = income;
}

public Customer()
{
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public void setIncome(int income)
{
this.income = income;
}

public int getIncome()
{
return this.income;
}

public Object clone() throws CloneNotSupportedException
{
try
{
return super.clone();
}
catch (CloneNotSupportedException cnse)
{
System.out.println("CloneNotSupportedException thrown " + cnse);
throw new CloneNotSupportedException();
}
}
}

public class MainClass
{
public static void main(String[] args)
{
try
{
Customer c= new Customer("Angel", 9000);
System.out.println(c);
System.out.println("The Customer name is " + c.getName());
System.out.println("The Customer pay is " + c.getIncome());

Customer cClone = (Customer) c.clone();
System.out.println(cClone);
System.out.println("The clone's name is " + cClone.getName());
System.out.println("The clones's pay is " + cClone.getIncome());

}
catch (CloneNotSupportedException cnse)
{
System.out.println("Clone not supported");
}
}
}

No comments:

Post a Comment

Website Design by Mayuri Multimedia