MATLAB Object-Oriented Programming

(Joyce) #1

Assigning an incompatible value to a property that uses class validation causes an error.


p.Number = datetime('now');


Error setting property 'Number' of class 'PropsWithClass':
Invalid data type. Value must be double or be convertible to double.


User-Defined Class for Validation


You can define a class to control the values assigned to a property. Enumeration classes
enable users to set property values to character vectors or string scalars with inexact
name matching.


For example, suppose that there is a class that represents a three-speed mechanical
pump. You can define an enumeration class to represent the three flow rates.


classdef FlowRate < int32
enumeration
Low (10)
Medium (50)
High (100)
end
end


The Pump class has a method to return the current flow rate in gallons per minute. Define
the Speed property as a FlowRate class.


classdef Pump
properties
Speed FlowRate
end
methods
function getGPM(p)
if isempty(p.Speed)
gpm = 0;
else
gpm = int32(p.Speed);
end
fprintf('Flow rate is: %i GPM\n',gpm);
end
end
end


Users can set the Speed property using inexact text.


Property Class and Size Validation
Free download pdf