cloneable in Java
By Saravanan Viewed: 31761 times Emailed: 103 times Printed: 101 times
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");
}
}
}
Comments(0)
Be the first one to add a comment
Latest Tutorials
More Latest News
Most Viewed Articles (in last 30 days)

