MATLAB Object-Oriented Programming

(Joyce) #1
that contains a handle object, you are actually copying the handle, not the object itself.
Therefore, your copy references the same object as the original object. Classes that
derive from the matlab.mixin.Copyable class can customize the way the copy method
copies objects of the class.

Class to Support Handle Copying

Suppose that you define a class that stores a handle in an object property. You want to be
able to copy objects of the class and want each copy of an object to refer to a new handle
object. Customize the class copy behavior using these steps:


  • Create a subclass of matlab.mixin.Copyable.

  • Override copyElement to control how the property containing the handle is copied.

  • Because the property value is a handle, create a new default object of the same class.

  • Copy property values from the original handle object to the new handle object.


The “HandleCopy” on page 7-39 class customizes copy operations for the property that
contains a handle object. The “ColorProp” on page 7-39 class defines the handle object
to assign to Prop2:

Create an object and assign property values:

a = HandleCopy;
a.Prop1 = 7;
a.Prop2 = ColorProp;

Make a copy of the object using the copy method inherited from
matlab.mixin.Copyable:

b = copy(a);

Demonstrate that the handle object contained by object a and b are independent.
Changing the value on object a does not affect object b:

a.Prop2.Color = 'red';
b.Prop2.Color

ans =

blue

7 Value or Handle Class — Which to Use

Free download pdf