MATLAB Object-Oriented Programming

(Joyce) #1
constructor if size restriction does not allow the use of an empty default value. The
default constructor must return an object of the correct size.

Sample Class Using Property Validation


The ValidateProps class defines three properties with validation.
classdef ValidateProps
properties
Location(1,3) double {mustBeReal, mustBeFinite}
Label(1,:) char {mustBeMember(Label,{'High','Medium','Low'})} = 'Low'
State(1,1) matlab.lang.OnOffSwitchState
end
end


  • Location must be a 1-by-3 array of class double whose values are real, finite
    numbers.

  • Label must be a char vector that is either 'High', 'Medium', or 'Low'.

  • State must be an enumeration member of the matlab.lang.OnOffSwitchState
    class (off or on).


Validation at Instantiation

Creating an object of the ValidateProps class performs the validation on implicit and
explicit default values:

a = ValidateProps

a =

ValidateProps with properties:

Location: [0 0 0]
Label: 'Low'
State: off

When creating the object, MATLAB:


  • Initializes the Location property value to [0 0 0] to satisfy the size and class
    requirements.

  • Sets the Label property to its default value, 'Low'. The default value must be a
    member of the allowed set of values. The empty char implicit default value would
    cause an error.


8 Properties — Storing Class Data

Free download pdf