• Post Reply Bookmark Topic Watch Topic
  • New Topic

would cloning help in this scenario?  RSS feed

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Class A hold a reference to object O. This object o is passed to other classes say Class B, C, D. I need class A to maintain its own copy means the changes made to object O at classes B,C,D should not affect the copy of class A. if i clone object O and send it to classes B, C, D will it work?

The sample implementation would be

Class A
{
TestObj obj;

// Obj get initialised in between
public void getObj()
{
return obj;
}
.
.
.
}

class B
{
//Class B holds reference to A
TestObj obj1 = a.getObj();
// modify obj1;
.
.
}

class C
{
//Class C holds reference to A
TestObj obj1 = a.getObj();
// modify obj1;
.
.
}

will it work if i clone obj before returning in getObj() method?


Regards,
Ajay.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. For details, see this section on Cloning from the 3rd edition of Thinking in Java.
 
Adam Richards
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not only will it work, but you must clone the object if you don't want the recipients to modify your copy of it (unless, of course, it's immutable; I assume from your question it isn't).
 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Thanks for your reply. what are the disadvantages of cloining technique?
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ajay Xavier:
hi,
...
will it work if i clone obj before returning in getObj() method?


Regards,
Ajay.


Maybe. You will have to decide for yourself what level of copying you need. What you are doing is called "defensive copying." Note that not only do you need this when you return an object, but you need this when you accept an object as well for the same reason.

The Full OO answer is to stop giving out references to the internals of your class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!