MATLAB: How to call the set-dot method on a subclass object to set a property of the superclass

classhierarchyMATLABoopset-dot

I have a superclass, and a subclass that inherits superclass. "xyz" property is defined in superclass. Superclass inherits "handle" class. I am trying to create a "set.xyz(obj)" method in subclass so that when "xyz" is being set, it calls that function but I get an error saying it cannot do that because "xyz" is in the superclass. Also, I have another method "update" in the subclass that I want to be executed whenever I set the "xyz" property by calling the set-dot method on the subclass object. Ideally I would like to be able to execute the following commands:
m = MySubClass;
m.xyz = 'a'; % this also calls an "update" method of the subclass
How can I call the set-dot method on a subclass object to set a property of the superclass?

Best Answer

You cannot define a "set.xyz" method in a subclass to set the "xyz" property of the superclass. This restriction prevents a subclass from overriding a superclass implementation and cannot be bypassed. However, in some situations superclass property needs to grant subclasses the ability to participate in the setting or getting of a property value, like in this case. To do so, a superclass "set" function can call a protected method to allow subclasses to participate in property access while still maintaining some level of control.
So the implementation of the two classes might look like this:
classdef MySuperClass < handle
properties
xyz
end
methods
function set.xyz(obj,value)
disp(['setting xyz in MySuperClass to ', value]);
obj.xyz = value; % updates the property
respondToXYZChange(obj) % calls the protected method
end
end
methods(Access = protected)
function respondToXYZChange(obj, value) % no function definition here
end
end
end
classdef MySubClass < MySuperClass
methods
function obj=MySubClass()
disp('!');
end
function update(obj)
disp('updating...');
end
end
methods(Access = protected)
function respondToXYZChange(obj) % call to the "update" method of subclass
obj.update();
end
end
end
>> m = MySubClass3;
!
>> m.xyz = 'a'
setting xyz in MySuperClass to a
updating...
m =
MySubClass3 with properties:
xyz: 'a'
>>
Executing the command:
m.xyz = 'a';
calls the superclass "set" method which sets the value of the property "xyz" and then calls the protected "respondToXYZChange" which is defined in the subclass to call the "update" method.