954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

shallow copying

how should i prevent the shallow copying?

every class i think i would need to copy i need to do the 'clone' function?
is there a 'copy constructor'?

the thing is -
i have a constructor that gets objects as parameters. how do i copy it into the data member?

i started to code now, after a long break, and i don't know how, but i forgotted lot of basic stuff.. :(
and lot of other things comes from c++ (i coded before)..

anilopo
Light Poster
29 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

You can always implement copy constructors in your class:

public Class yourClass
{
   public yourClass(yourClass yourClassObject)
   {
      //implement
   }
}

Other than that, you need to read the API about mutable and immutable objects to help you decide how to implement their copy in the constructor.

apines
Practically a Master Poster
633 posts since Apr 2007
Reputation Points: 129
Solved Threads: 55
 

and if i do:

MyClass a,b;
// ... there is now something in b
a=b;

what would happen?

anilopo
Light Poster
29 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

Objects are always by reference in Java, which means that a=b will point a to the place in the heap the b resides - any future changes to b will affect a as well.

apines
Practically a Master Poster
633 posts since Apr 2007
Reputation Points: 129
Solved Threads: 55
 
Objects are always by reference in Java, which means that a=b will point a to the place in the heap the b resides - any future changes to b will affect a as well.

does it means that if a is local b would hold garbage?

anilopo
Light Poster
29 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

You were talking about objects - in Java objects are always on the heap, never local on the stack, so the scenario you have mentioned cannot happen.

apines
Practically a Master Poster
633 posts since Apr 2007
Reputation Points: 129
Solved Threads: 55
 

wow, i'm confused..
thx on all the help!

anilopo
Light Poster
29 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

Well, it was not my intention to confuse you - what are you confused about? I'll try to explain it more thoroughly.

apines
Practically a Master Poster
633 posts since Apr 2007
Reputation Points: 129
Solved Threads: 55
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: