Why does copying a Java object only make a shallow copy?

1 view (last 30 days)
When I assign one variable containing a Java object to another and make changes to the original object, both are changed. Why is this?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!