Properties Containing Objects

Assigning to Read-Only Properties Containing Objects

When a class defines a property with private or protected SetAccess, and that property contains an object which itself has properties, assignment behavior depends on whether the property contains a handle or a value object:

  • Handle object – you can set properties on handle objects contained in read-only properties

  • Value object – you cannot set properties on value object contained in read-only properties.

These example classes illustrate this assignment behavior:

  • ReadOnlyProps – class with two read-only properties. The class constructor assigns a handle object of type HanClass to the PropHandle property and a value object of type ValClass to the PropValue property.

  • HanClass – handle class with public property

  • ValClass – value class with public property

classdef ReadOnlyProps
   properties(SetAccess = private)
      PropHandle
      PropValue
      
   end
   methods
      function obj = ReadOnlyProps
         obj.PropHandle = HanClass;
         obj.PropValue = ValClass;
      end
   end
end

classdef HanClass < handle
   properties
      Hprop
   end
end 

classdef ValClass
   properties
      Vprop
   end
end

Create an instance of the ReadOnlyProps class:

a = ReadOnlyProps

a = 

 ReadOnlyProps with properties:

    PropHandle: [1x1 HanClass]
     PropValue: [1x1 ValClass]

Use the private PropHandle property to set the property of the HanClass object it contains:

class(a.PropHandle.Hprop)

ans =

double
a.PropHandle.Hprop = 7;

Attempting to make an assignment to the value class object property is not allowed:

a.PropValue.Vprop = 11;
You cannot set the read-only property 'PropValue' of ReadOnlyProps.
Was this topic helpful?