MATLAB Object-Oriented Programming

(Joyce) #1

Mutable and Immutable Properties


In this section...
“Set Access to Property Values” on page 8-22
“Define Immutable Property” on page 8-22

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 during construction. 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.


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 = date;
end

8 Properties — Storing Class Data

Free download pdf