how to implementing the cloneable interfacethe


How to Implementing the Cloneable Interface

The java.lang.Object class contains a clone() method which returns a bitwise copy of the current object.
protected native Object clone() throws CloneNotSupportedException
Not all objects are cloneable. It particular only examples of classes that implement the Cloneable interface can be cloned. Trying to clone an object in which does not implement the Cloneable interface throws a CloneNotSupportedException.
For instance, to make the Car class cloneable, you simply declare that it implements the Cloneable interface. Because this is only a marker interface, you do not requires to add any methods to the class.

public class Car extends MotorVehicle implements Cloneable {

// ...

}

For example

Car c1 = new Car("New York A12 345", 150.0);
Car c2 = (Car) c1.clone();

Most classes in the class library do not implement Cloneable so their examples are not cloneable.

Most of the time, clones are shallow copies. Instead if the object being cloned holds a reference to another object A, then the clone holds a reference to the same object A, not to a clone of A. If this isn't the behavior you need, you can override clone() yourself.
You may also override clone() if you want to make a subclass uncloneable, while one of its superclasses does implement Cloneable. In this case simply use a clone() method in which throws a CloneNotSupportedException. For example,

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Can't clone a SlowCar");
}
You may also need to override clone() to make it public instead of protected. In this case, you can simply fall back on the superclass implementation. For instance,

public Object clone() throws CloneNotSupportedException {
return super.clone();
}

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: how to implementing the cloneable interfacethe
Reference No:- TGS0284840

Expected delivery within 24 Hours