MATLAB Object-Oriented Programming

(Joyce) #1
MATLAB creates the default value by calling the class constructor with no arguments.
The class must have a constructor that returns an object of the specified size when called
with no input arguments or you must specify a default value for the property that satisfies
the property size restriction. For more information, see “Default Values Per Size and
Class” on page 8-37.

Using Class Validation

The PropsWithClass class defines two properties with class definitions:


  • Number — Values must be of class double or convertible to double.

  • Today — Values must be of class char or convertible to char. The default value is the
    char vector returned by the date function.


classdef PropsWithClass
properties
Number double
Today char = date
end
end

Create an object of the PropsWithClass class.

p = PropsWithClass

p =

PropsWithClass with properties:

Number: []
Today: '10-Sep-2016'

MATLAB performs conversions from any compatible class to the property class. For
example, assign a datetime array to the Today property.

p.Today = [datetime('now'),datetime('tomorrow')];
disp(class(p.Today))

ans =

char

Because the datetime class has a char converter, you can assign a datetime array to
the Today property.

8 Properties — Storing Class Data

Free download pdf