Define class properties within aproperties
block:
classdefClassNameproperties(PropertyAttributes)PropertyName size class {validation functions}=DefaultValueendend
Property attributes apply to all properties defined within the block. To define properties with different attributes, use multipleproperties
blocks. All property attributes have default values. For a list of property attributes, seeProperty Attributes.
Restrict the size, class, and other aspects of values assigned to properties in the property definition. For more information, see验证的财产价值es.
Optionally assign default values to the property in theproperties
block. MATLAB®evaluates the assignment statement when the class is first referenced or when loading a saved object. For more information, seeProperty Definition.
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, seeWhen MATLAB Evaluates Expressions.
The following class defines three properties.Model
andColor
use default attribute values, resulting in public read and write access.SerialNumber
has read-only access by object users. Assign theSerialNumber
property value from a class member function, such as the constructor or other class method.
classdefNewCarpropertiesModel Colorendproperties(SetAccess = private) SerialNumberendmethods...endend
Use dot notation to access property value.
A = NewCar
A = NewCar with properties: Model: [] Color: [] SerialNumber: []
Set theModel
andColor
properties:
A.Model ='XGT7000'; A.Color ='Red';
Add a constructor to theNewCar
class to set property values:
classdefNewCarpropertiesModel Colorendproperties(SetAccess = private) SerialNumberendmethodsfunctionobj = NewCar(model,color) obj.Model = model; obj.Color = color; obj.SerialNumber = datenum(datetime('now'));endendend
A = NewCar('XGT7000','Red')
A = NewCar with properties: Model: 'XGT7000' Color: 'Red' SerialNumber: 7.362456078531134e+05