Thursday, October 31, 2013

Myths regarding java cloning (Override clone method)



Myths regarding java cloning (Override clone method)

There are lots and lots of good material around us on CLONING. I don’t want to re-write those things here. The purpose of this post is just to clear the confusion that is there among many of us that we need to override clone method.

Public class Person implements Cloneable {
      private int id;
      private String personName;
      // getter setters

      public Person(int id, String name) {
            this.id = id;
            this.personName = name;
      }

      public Object clone() throws CloneNotSupportedException {
            return super.clone();
      }


      //access modifier can be anything like private, default, protected, public


      private Object myClone() throws CloneNotSupportedException {
            return super.clone();
      }
}

Both the methods ‘clone’ and ‘myClone’ will return a clone of person object. E.g.
      Person p = new Person(1,”Manish”);
      Person cloneA = (Person)p.clone();
      Person cloneB = (Person)p.myClone();

Thanks
Manish Kumar Agarwal
Manish.java@outlook.com

No comments:

Post a Comment