Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 3
    It is wholly dependent upon what you are trying to accomplish, there are use cases for both ways. FYI, java's default object.clone() method does a shallow copy, so, in summary, the former will be susceptible to changes in the object, while your latter example is immune to changes to the object itself, but susceptible to changes in objects referred to by the clone. Commented Mar 31, 2016 at 18:36
  • 'susceptible to changes in objects referred to by the clone' - yes, thats why I said assuming the fields in MyOtherClass are of primitive type. Otherwise I'd need a copy constructor. Commented Mar 31, 2016 at 19:04
  • In Java, clone is seldom a good idea :) Commented Mar 31, 2016 at 19:50
  • 2
    Make MyOtherClass immutable. The only reason not to is performance. In such case, copying it is also out of the question and you will just have to expose internals of your class. Commented Mar 31, 2016 at 20:21
  • @Banthar what I mean is: suppose there's a private int[] myField in my class with a setter. The caller might set the array (with the setter) and then modfy the array in their code. Cloning the array on set eliminates the problem. It's not that I want to assign to a field only once (and final would make sense then). Commented Mar 31, 2016 at 22:01