CODE
class ObjectDemo implements Cloneable // LINE A
{
public static void main(String[] args) throws CloneNotSupportedException
{
ObjectDemo obj1 = new ObjectDemo();
ObjectDemo obj2 = (ObjectDemo)obj1.clone(); // LINE B
if(obj1.equals(obj2))
System.out.println("obj1 equals to obj2");
else
System.out.println("obj1 not equals to obj2");
}
}
obj1 not equals to obj2
In the above program we used the methods of Object
class. Normally if the class object which is invoking clone()
method don't implement the Cloneable
interface JVM
will throw CloneNotSupportedException
. So at LINE A
in our ObjectDemo
program implements the Cloneable
. Here we don't need to provide the body for the clone()
method because super class has it's implementation for it so when we say obj1.clone()
it will call the Object
class method. Also see at LINE B
we typecasted to ObjectDemo
because the return type of clone()
is Object
so we need to typecast it to ObjectDemo
.
Cloneable
. The method clone()
will throw CloneNotSupportedExceptionLINE B
object.getClass().getSimpleName()
obj1
.