Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding clone method

 
abin joy
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what does the clone method in the Object class dO?
In which context we use the clone function?
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want you to read its docs first !

clone method , as far as I know , returns an different object from heap of same type with may be same values .

When you do something like this,



This two objects are referring to same object on heap !

But when you do something like this ,



Here obj2 is totally different object of type 'CloneableObject'..

I know this much only , fellow rancher ll explain us in detail !
[ September 06, 2008: Message edited by: Sagar Rohankar ]
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sagar Rohankar:
I want you to read its docs first !

...

Here obj2 is totally different object of type 'CloneableObject'..

Have you read your own link? It clearly says that although it is usual that obj1 and obj2 are different objects, they can be the same.

As far as I know, Object.clone() creates a new instance of the same class and makes shallow copies of all fields. In code, it's something similar to this:

That's why, if you don't want to share the objects, you will need to copy those:
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:

Have you read your own link? It clearly says that although it is usual that obj1 and obj2 are different objects, they can be the same.



You may misinterpret it ! At the start of my thread I clearly wrote this ,

clone method , as far as I know , returns an different object from heap of same type with may be same values .


Surely the object is different but they may or may not have same values or pass the Object#equal() test ! (Thats totally depends upon the implementation of clone() method )
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But they don't need to be different. clone() is very much allowed to return "this":
The general intent is that, for any object x, the expression:

will be true, and that the expression:

will be true, but these are not absolute requirements. While it is typically the case that:

will be true, this is not an absolute requirement.

So x.clone() == x is most definitely allowed - highly unusual, but allowed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic