Interview Questions

Java cloneable interface - What is cloneable interface ?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

Java cloneable interface - What is cloneable interface ?

1) The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object (that is, a clone) 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 simply an exact copy of the original.

2)The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object (that is, a clone) 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 simply an exact copy of the original.

3)The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object (that is, a clone) 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 simply an exact copy of the original.

The Example of cloneable interface-

class TestCloneDemo implements Cloneable {
int a;
double b;

// This method calls Object's clone().
TestCloneDemo cloneTest() {
try {
// call clone in Object.
return (TestCloneDemo) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("Cloning not allowed.");
return this;
}
}
}

public class CloneDemo {
public static void main(String args[]) {
TestCloneDemo x1 = new TestCloneDemo();
TestCloneDemo x2;
x1.a = 15;
x1.b = 35.05;
x2 = x1.cloneTest(); // clone x1
System.out.println("x1: " + x1.a + " " + x1.b);
System.out.println("x2: " + x2.a + " " + x2.b);
}
}

(Continued on next question...)

Other Interview Questions