Methods of a Object class :
using clone method of Object class
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");
}
}
OUTPUTobj1 not equals to obj2
DESCRIPTIONIn 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
.
THINGS TO TRY
- Now see what if our class don't implement the
Cloneable
. The method clone()
will throw CloneNotSupportedException
- Also see what happens if don't do the typecasting at
LINE B
- To find the class name any object we need to do as follows.
Syntax :
object.getClass().getSimpleName()
now find and print the class name of obj1
.