MATLAB: Modifying an immutable/protected variable of a subclass in a superclass method

oopprogramming

Hi,
I'm trying to modify an immutable/protected property of a sub class, using a superclass method or an external utility function (I'm trying to use this function in the subclass's constructor, of course).
Example (of what I would like to do):
classdef Sup
methods
function self = setProperties(self, varargin)
% This method sets the properties of the class
% the input arguments come in the form 'propname1', val1, 'propname2', val2, ...
...
end % setProperties
end % methods

end % classdef Sup
classdef sub < Sup
properties (SetAccess = immutable)
prop1
prop2
prop3
end % properties
methods
function self = sub(varargin)
% constructor
self = setProperties(self, varargin)
end % sup
end % methods
end % classdef sub
>> SomeObj = sub('prop1', 1, 'prop2', 10, 'prop3', 100);
This code doesn't work, I get the error message 'You cannot set the read-only property 'prop1' of sub.'
I'm OK with setting sub's properties to be protected, but I wouldn't want them to be public. I'm also OK with the idea that setProperties would be an external utility function (not defined in the superclass), but then again, I'm not able to use setProperties in the constructor of sub.
Would appreciate your help on that.
Thank you,
Avihay

Best Answer

You're trying to break the fundamental model of OOP: encapsulation. The whole concept of protected properties is that only the class (or its subclasses) can modify them. A superclass has no way to modify the properties of its subclasses. For that matter, there's no guarantee that a subclass would have the propery that it's trying to modify.
Secondly, why are you trying this indirect method for setting properties? Can't you just set the properties of the subclass the normal way? Or even just override your setProperties method in the subclass?
If you really want to set the properties from the superclass, what you can do though is have a method setsubProperties in the superclass that you then override in the subclass. You dispatch to this method from the setProperties method:
classdef Sup < handle %has to be a handle class to modify its own properties
methods
function setProperties(this, varargin)
this.setsubProperties(varargin);
end
end
methods (Access = protected)
function setsubProperties(this, varargin)
error('function must be overriden');
end
end
end
classdef sub < Sup
methods (Access = proteced)
function setsubProperties(this, varargin)
for varg = 1:2:numel(varargin)
%...
end
end
end
end