Properties Containing Objects - MATLAB & Simulink (original) (raw)

Main Content

Assigning Objects as Default Property Values

MATLAB® evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.

Note

Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create an instance of the class.

For more information on the evaluation of expressions that you assign as property default values, see When MATLAB Evaluates Expressions.

Assigning to Read-Only Properties Containing Objects

When a class defines a property with private or protected SetAccess, and that property contains an object which itself has properties, assignment behavior depends on whether the property contains a handle or a value object:

Assignment Behavior

These classes illustrate the assignment behavior:

classdef ReadOnlyProps properties(SetAccess = private) PropHandle PropValue
end methods function obj = ReadOnlyProps obj.PropHandle = HanClass; obj.PropValue = ValClass; end end end

classdef HanClass < handle properties Hprop end end

classdef ValClass properties Vprop end end

Create an instance of the ReadOnlyProps class:

a =

ReadOnlyProps with properties:

PropHandle: [1x1 HanClass]
 PropValue: [1x1 ValClass]

Use the private PropHandle property to set the property of the HanClass object it contains:

class(a.PropHandle.Hprop)

Attempting to make an assignment to the value class object property is not allowed:

You cannot set the read-only property 'PropValue' of ReadOnlyProps.

See Also

Topics