Must dependent properties in abstract class be redefined in every concrete subclass?
조회 수: 7 (최근 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에서 Methods에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!