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.
As perits documentationmatlab.mixin.Copyable does not make a deep copy of the object properties even if they themselves derived from copyable:"In making a shallow copy, MATLABĀ® does not call copy recursively on any handles contained in property values." You actually have to override thecopyElement to make the copy yourself:
classdef Pipe < matlab.mixin.Copyable
properties
PipeName;
PipeVault;
UnLock;
Units;
end
methods (Access = protected)
function thiscopy = copyElement(this)
thiscopy = copyElement@matlab.mixin.Copyable(this); %shallow copy of all elements
thiscopy.PipeVault = copy(this.PipeVault); %Deep copy of pipevault
Best Answer