How can I call the set-dot method on a subclass object to set a property of the superclass?
Show older comments
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?
Accepted Answer
More Answers (1)
Robert
on 27 Aug 2021
How about 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
if class(obj) == "MySubClass"
respondToXYZChange(obj) % calls the subclass method
end
end
end
end
classdef MySubClass < MySuperClass
methods
function respondToXYZChange(obj)
disp("updating...")
end
end
end
This way, there is no need to define respondToXYZChange in the superclass.
2 Comments
Steven Lord
on 27 Aug 2021
But this approach means that the superclass needs to be modified any time a new subclass gets defined, to add it to the list of classes that set.xyz needs to know about. This is a violation of the open-closed principle.
Robert
on 27 Aug 2021
That's definitely something to take into account, yes!
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!