How to set object property to Abstract class

43 views (last 30 days)
I am getting errors when I try to set an object property type to an Abstract class "matlab.mixin.Heterogeneous" as below:
classdefdemoClass
properties
TestPropertymatlab.mixin.Heterogeneous
end
methods
functionobj = demoClass
% constructor that does not affect the property
end
end
end
The error I get is
>> demoClass
Errordefining property 'TestProperty' of class 'demoClass'. Class matlab.mixin.Heterogeneous is abstract. Specify a default value for property TestProperty.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 28 Jul 2020
To specify an Abstract class as a property for a MATLAB class, you must also specify a default value for the property which is a class that is derived from the abstract class you specified.
The code below demonstrates how the code you provided might be modified to accomplish this workflow.
classdefdemoClass
properties
TestPropertymatlab.mixin.Heterogeneous= rootClass
end
methods
functionobj = demoClass
% constructor that does not affect the property
end
end
end
classdefrootClass < matlab.mixin.Heterogeneous
methods
functionobj = rootClass
end
end
end
现在你应该能够实例化instance of "demoClass":
>> demoClass
ans =
demoClasswith properties
TestProperty: [1×1 rootClass]

More Answers (1)

Jim Svensson
Jim Svensson on 25 Aug 2021
It is stupid Matlab language design. It should be normal to define a property to be an abstract class type. As long as it is empty (array with 0 elements) it is not a problem, and then only assign concrete sub-classes to the property.

Tags

下载188bet金宝搏


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!