Alternatively, if there is a way to make the super class properties all mutable and the subclass properties selectively immutable, I could work with that also.
How to make an inherited immutable super class property mutable in the sub-class?
5 次查看(过去 30 天)
显示 更早的评论
I have a class which has immutable properties and I want some sub-classes to be able to modify these properties. Obviously it raises an error if you try to redefine the variable so is there a correct way to do this?
Example:
classdef Super < handle
properties (SetAccess = immutable)
Prop1
end
properties
Prop2
end
end
classdef Sub < Super
properties
Prop1
Prop2
end
end
subObj = Sub
Error using Sub
Cannot define property 'Prop1' in class 'Sub' because the property has already been defined in the
superclass 'Super'.
Ideally I'd like to avoid writing custom set/get methods and use the 'immutable' feature in the super class.
UPDATE:
I also tried to use an abstract super class:
classdef (Abstract) Super < handle
properties (Abstract)
Prop1
Prop2
end
end
classdef Sub < Super
properties (SetAccess = immutable)
Prop1 = 0
end
properties
Prop2
end
methods
function obj = Sub(p2)
obj.Prop2 = p2;
end
end
end
but I still get an error:
Error using Sub
The definition of property 'Prop1' in class 'Sub' differs from its definition in the superclass
'Super'. This is caused by either conflicting access permissions or differing values of the
Constant attribute.
3 个评论
Steven Lord
2022-6-14
I have a class which has immutable properties and I want some sub-classes to be able to modify these properties.
If the author of the superclass wanted those properties to be modifiable after the superclass constructor has fixed them, the author wouldn't have made them immutable. So what's your use case for overriding the superclass author's intent?
回答(1 个)
Steven Lord
2022-6-14
Just off the top of my head and based on the minimal information about your design, based on the fact that you said the subclasses should be able to decide if the gain is fixed or can vary with time I would likely make Gain an Abstract property and computeGain an Abstract method in the superclass.
In that case a FixedGainFilter subclass could define Gain to be a double array and have a computeGain method that just returns that property. A VariableGainFilter subclass could define Gain to be a function handle of time and have computeGain evaluate that function handle at the current time. Whatever methods in the superclass or subclass need the gain at a particular time would go through the computeGain interface.
I have not tried this to see how well it works (or if it works) but I believe it will.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Class Introspection and Metadata 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!