Interview Questions

Implementing the Cloneable Interface

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

Implementing the Cloneable Interface

The java.lang.Object class contains a clone() method that returns a bitwise copy of the current object.

protected native Object clone() throws CloneNotSupportedException

Not all objects are cloneable. It particular only instances of classes that implement the Cloneable interface can be cloned. Trying to clone an object that does not implement the Cloneable interface throws a CloneNotSupportedException.

For example, to make the Car class cloneable, you simply declare that it implements the Cloneable interface. Since this is only a marker interface, you do not need to add any methods to the class.

public class Car extends MotorVehicle implements Cloneable {

// ...

}

(Continued on next question...)

Other Interview Questions