Immutable properties and subclass constructors
显示 更早的评论
Is it possible to somehow set immutable superclass properties in a subclass constructor? It seems not, but maybe I'm just misinterpreting the documentation and error messages and this is possible somehow?
In case this doesn't make sense, my motivation is this: I've written a fairly nice data-analysis object that I use as a superclass all the time. It loads data from the data acquisition tool we normally use, and I have different subclasses for different experiments, which have different analysis requirements but most of the basics are the same (and located in the superclass).
Now I'd like to re-use all that code by loading data (of essentially the same form) but from a different filetype (new constructor required) into the properties expected by the superclass. I could just make the properties protected in the superclass (instead of immutable), but I'd really like them to only be changed within the constructor of the new subclass.
Or maybe I should be approaching this in a different way entirely?
采纳的回答
更多回答(1 个)
Is it possible to somehow set immutable superclass properties in a subclass constructor?
Yes. The subclass constructor can call the superclass constructor and use that to set the immutable property, e.g.,
classdef myclass
properties (SetAccess=immutable)
p;
end
methods
function obj=myclass(pval)
obj.p=pval;
end
end
end
classdef mysubclass < myclass
methods
function obj=mysubclass(pval)
obj=obj@myclass(pval);
end
end
end
类别
在 帮助中心 和 File Exchange 中查找有关 Subclass Definition 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!