Topics Index

using clone method of Object class - Java Example Program

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
            System.out.println("obj1 equals to obj2");
            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.

  • 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 :
    now find and print the class name of obj1.

© meritcampus 2019

All Rights Reserved.

Open In App