Main Content

Class Properties

The Properties Block

Define class properties within apropertiesblock:

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 multiplepropertiesblocks. 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 thepropertiesblock. 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.

Properties with Different Attributes

The following class defines three properties.ModelandColoruse default attribute values, resulting in public read and write access.SerialNumberhas read-only access by object users. Assign theSerialNumberproperty value from a class member function, such as the constructor or other class method.

classdefNewCarpropertiesModel Colorendproperties(SetAccess = private) SerialNumberendmethods...endend

Access to Property Values

Use dot notation to access property value.

A = NewCar
A = NewCar with properties: Model: [] Color: [] SerialNumber: []

Set theModelandColorproperties:

A.Model ='XGT7000'; A.Color ='Red';

Add a constructor to theNewCarclass 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

Related Topics