MATLAB Object-Oriented Programming

(Joyce) #1

Initialize Property Values


There are two basic approaches to initializing property values:


  • In the property definition — MATLAB evaluates the expression only once and assigns
    the same value to the property of every instance.

  • In a class constructor — MATLAB evaluates the assignment expression for each
    instance, which ensures that each instance has a unique value.


For more information on the evaluation of expressions that you assign as property default
values, see “When MATLAB Evaluates Expressions” on page 6-13.

Property Default Values


Within a properties block, you can control an individual property's default value.
Assign default values as a value or MATLAB expressions. Expressions cannot reference
variables. For example:


  • Prop1 — No assignment results in empty [] default value

  • Prop2 — Assign character array as default value

  • Prop3 — Assign result of expression as default value


classdef ClassName
properties
Prop1
Prop2 = 'some text'
Prop3 = sin(pi/12)
end
end

If the class definition does not specify a default property value, MATLAB sets the property
value to empty double ([]).

NoteEvaluation 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 “Evaluation of Expressions in Class Definitions” on page 6-10 and “Properties
Containing Objects” on page 8-66.

8 Properties — Storing Class Data

Free download pdf