wood burning stoves 2.0
The moose likes Java in General and the fly likes A question on object cloning. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "A question on object cloning." Watch "A question on object cloning." New topic

A question on object cloning.

Vanchi Nathan
Ranch Hand

Joined: Feb 24, 2004
Posts: 107
hello everyone,

i have tried the following code:
The question is the why is the line
(firstObj == secondObj)
not returning a true value?

Thanks in advance.

Best regards,<br /> <br />vanchin
Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
API for clone() method of java.lang.Object class states:

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x will be true, and that the expression:
x.clone().getClass() == x.getClass()will be true, but these are not absolute requirements.

While it is typically the case that:
x.clone().equals(x)will be true, this is not an absolute requirement.

Further more, the API states (and this point is vital):

Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547

because it is not the same object but a clone...
remember: == checks if the reference points to the same object in memory, equals() checks if the objects are having the same state.

if firstObj == secondObj would be true, then the clone operation would actualy just return a reference to itself... which is not the intent. clone() should return a new object with the same state as the object you called clone() on.

do i make sense ?

I agree. Here's the link: http://aspose.com/file-tools
subject: A question on object cloning.
It's not a secret anymore!