MATLAB: When I have nested objects, changing the parameter of one object changes the same parameter in others

handleMATLAB

I am working with two handle classes, Class1 and Class2, defined as follows:
classdef Class1 < handle
properties
a = Class2;
end
end
classdef Class2 < handle
properties
b = 1;
end
end
If I create two separate instances of Class1 and adjust the value of parameter 'b' in the nested instance of Class2, the value of 'b' in both instances of Class 1 change. Is this supposed to happen?

Best Answer

This is an intended behavior for handle classes, and is documented here:
When a constructor for a handle class is placed in the 'properties' section of a class definition, MATLAB creates one generic object of that class and makes the property a handle to that object. If multiple constructors for the same class appear in the 'properties' section, or if multiple objects are created that have the same constructor in their 'properties', a handle to that same generic object are assigned to those properties. In other words, MATLAB does not create a new object every time the constructor is called in the properties section, instead it creates one object and links every constructor call to it.
This behavior can be eliminated by moving the constructor call from the properties section to the constructor of the object. For example, Class1 in the questions can be changed to:
classdef Class1 < handle
properties
a;
end
methods
function obj = Class1()
obj.a = Class2();
end
end
end