Mutable and Immutable Properties
Set Access to Property Values
The property SetAccess
attribute enables you to determine under what conditions code can modify object property values. There are four levels of set access that provide varying degrees of access to object property values:
SetAccess = public
— Any code with access to an object can set public property values. There are differences between the behavior of handle and value classes with respect to modifying object properties.SetAccess = protected
— Only code executing from within class methods or methods of subclasses can set property values. You cannot change the value of an object property unless the class or any of its subclasses defines a method to do so.SetAccess = private
— Only the defining class can set property values. You can change the value of an object property only if the class defines a method that sets the property.SetAccess = immutable
— Property value is set in the constructor. You cannot change the value of an immutable property after the object is created. Set the value of the property as a default or in the class constructor. You cannot define a property set method (set.
) for an immutable property.PropertyName
For related information, see Properties Containing Objects.
Define Immutable Property
In this class definition, only the Immute
class constructor can set the value of the CurrentDate
property:
classdef Immute properties (SetAccess = immutable) CurrentDate end methods function obj = Immute obj.CurrentDate = datetime("today"); end end end
a = Immute
a = Immute with properties: CurrentDate: 09-Jun-2022