"MATLAB assigns properties to the specified default values only once when MATLAB loads the class definition. Therefore, if you initialize a property value with a handle-class constructor, MATLAB calls this constructor only once and every instance references the same handle object. If you want a property value to be initialized to a new instance of a handle object each time you create an object, assign the property value in the constructor." Because of this:
- All the innermost_inst properties of the Inner object are references to the same Innermost handle object.
- All the inner_inst properties of Outer1 handle objects are references to the same Inner handle object.
- All inner_inst properties of Outer2 handle objects are references to the same Inner handle object.
- But the inner_inst properties of Outer1 handle objects are not the same object as the inner_inst properties of Outer2 handle objects.
Now what does the == operator do for handle classes? As stated in the "Determining Equality of Objects" section of this documentation page, "Equality for handle objects means that the handle variables refer to the same object." That's why asking if the two innermost_inst properties are == returns true, while asking if the two inner_inst properties are == returns false for an instance of Outer1 and an instance of Outer2. If you want all four of those comparisons to return true, you want to use isequal.
isequal(out1a.inner_inst, out1b.inner_inst)
isequal(out1a.inner_inst, out2b.inner_inst)
isequal(out1a.inner_inst.innermost_inst, out1b.inner_inst.innermost_inst)
isequal(out1a.inner_inst.innermost_inst, out2b.inner_inst.innermost_inst)
If you want each instance of Outer1 to have a different instance of Inner as its inner_inst property, set that property in the Outer1 constructor. Similarly, if you want each instance of Inner to have a different Innermost as its innermost_inst property, set that in the Inner constructor.
Best Answer