Main Content

Class Properties

The Properties Block

Define class properties within a properties block:

classdef ClassName
   properties (PropertyAttributes)
      PropertyName size class {validation functions} = DefaultValue
   end
end

Property attributes apply to all properties defined within the block. To define properties with different attributes, use multiple properties blocks. All property attributes have default values. For a list of property attributes, see Property Attributes.

Restrict the size, class, and other aspects of values assigned to properties in the property definition. For more information, see Validate Property Values.

Optionally assign default values to the property in the properties block. MATLAB® evaluates the assignment statement when the class is first referenced or when loading a saved object. For more information, see Property 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, see When MATLAB Evaluates Expressions.

Properties with Different Attributes

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

classdef NewCar
   properties
      Model
      Color
   end
   properties (SetAccess = private)
      SerialNumber
   end
   methods
   ...
   end
end

Access to Property Values

Use dot notation to access property value.

A = NewCar
A = 

  NewCar with properties:

           Model: []
           Color: []
    SerialNumber: []

Set the Model and Color properties:

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

Add a constructor to the NewCar class to set property values:

classdef NewCar
   properties
      Model
      Color
   end
   properties (SetAccess = private)
      SerialNumber
   end
   methods
      function obj = NewCar(model,color)
         obj.Model = model;
         obj.Color = color;
         obj.SerialNumber = datenum(datetime('now'));
      end
   end
end
A = NewCar('XGT7000','Red')
A = 

  NewCar with properties:

           Model: 'XGT7000'
           Color: 'Red'
    SerialNumber: 7.362456078531134e+05

Related Topics