Must dependent properties in abstract class be redefined in every concrete subclass?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Matt J
le 7 Mar 2023
Modifié(e) : Matt J
le 7 Mar 2023
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 commentaires
Matt J
le 7 Mar 2023
Modifié(e) : Matt J
le 7 Mar 2023
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Methods dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!