This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes clone an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "clone an object" Watch "clone an object" New topic

clone an object

rucha kulkarni

Joined: Aug 05, 2010
Posts: 22

How do I clone an object in java without using clone method?

Swastik Dey

Joined: Jan 08, 2009
Posts: 1447

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37874
Useful site, but it misses one thing out. It implies the return type of clone() is Object. Since Java5, it has been possible to use covariant return types, so you can have a clone() method in class Foo which returns a Foo reference.
The serialisation solution is a well‑known cheat, which does work, but only if the class implements Serializable. It also has slower performance.
Better solutions: If you want to copy your object, you can give the class a copy() method (rather like this, or a copy constructor, or a factory method which copies an object.
Better still, make your class immutable. Then you can forget all about cloning, copying, etc, because that will cease to be a problem.
It is sorta covered in the JavaRanch Style Guide.
subject: clone an object
Similar Threads
The "this" keyword and the constructor.
usage of "this"
how this program works i didn't understand
Fetch 10K rows from table