Must dependent properties in abstract class be redefined in every concrete subclass?
9 次查看(过去 30 天)
显示 更早的评论
I have an abstract superclass that defines some dependent properties, which an object of any concrete subclass should be able to return. Each subclass will have a unique method for deriving the value of each of these properties from its stored data, as implemented by a get.property method.
To do this it appears that I have to replicate the block of dependent properties from the superclass in every subclass. Is this correct? It seems redundant, since the properties are already defined in the superclass.
2 个评论
采纳的回答
Matt J
2023-3-7
编辑:Matt J
2023-3-7
If your abstract base class defines the Dependent property, then its get.property() method must also be defined in the abstract base class. However, the get.property() method can consist of some steps that will be common to all subclasses and some steps that are customized by the subclasses, e.g.,
>> obj=mysubclass;
>> obj.a
This is the get.a of mysubclass
ans =
0.7094 0.6797
0.7547 0.6551
0.2760 0.1626
>> obj.a(:,1)
This is the get.a of mysubclass
ans =
0.1190
0.4984
0.9597
classdef myclass
properties (Dependent)
a
end % methods
methods
function val=get.a(obj)
disp("This is the get.a of "+class(obj)) %common step
val=obj.customizedValues;
end
end
methods (Abstract)
val=customizedValues(obj)
end
end % class
classdef mysubclass<myclass
methods
function val=customizedValues(obj)
val=rand(3,2);
end
end
end
3 个评论
Matt J
2023-3-7
编辑:Matt J
2023-3-7
Is there a fundamental reason why the subclasses can't inherit the property definitions from the base class and then have their individual implementations of the require set/get methods?
As I recall, the official MathWorks reason is that making set/get methods overloadable would be prone to errors and conflicts with base class methods. If the parent set method forces a property value to be positive for example, it's supposed to reflect something you can always assume about that property throughout the class hierarchy. If a child class could then relax the requirement that the property value be positive, parent class methods could then fail to support child instances as inputs.
On the other hand, if each subclass has to redefine the dependent properties anyway, I'm not sure there's even any reason to define them in the base class at all. ??
There wouldn't be. You should only define properties and methods in a base class if, as in my example, there is some common feature to them that you want to inherit from the base class
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Subclass Definition 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!