MATLAB: Does copying a Java object only make a shallow copy

assignmentcopyjavaMATLAB

When I assign one variable containing a Java object to another and make changes to the original object, both are changed. Why is this?

Best Answer

Copying a Java object only makes a shallow copy of the object. A new Java object of A's class is not created. So if you have a Java object A, the command:
B = A;
creates B as a reference to A. Any change in A will be reflected in B, and vice versa. This is because A and B actually refer to the same Java object.
In order to make a deep copy of A, you need to invoke a cloning method for the class if one is defined.