How to set object property to Abstract class

24 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2020 年 7 月 28 日
回答済み: Jim Svensson 2021 年 8 月 25 日
I am getting errors when I try to set an object property type to an Abstract class "matlab.mixin.Heterogeneous" as below:
classdef demoClass
  properties
    TestProperty matlab.mixin.Heterogeneous   
  end
  methods
    function obj = demoClass
      % constructor that does not affect the property
    end
  end
end
The error I get is
>> demoClass
Error defining property 'TestProperty' of class 'demoClass'. Class matlab.mixin.Heterogeneous is abstract. Specify a default value for property TestProperty.

採用された回答

MathWorks Support Team
MathWorks Support Team 2020 年 7 月 28 日
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.
classdef demoClass
  properties
    TestProperty matlab.mixin.Heterogeneous = rootClass
  end
  methods
    function obj = demoClass
      % constructor that does not affect the property
    end
  end
end
classdef rootClass < matlab.mixin.Heterogeneous
  methods
    function obj = rootClass
    end     
  end
end
And now you should be able to instantiate an instance of "demoClass":
>> demoClass
ans =
demoClass with properties
TestProperty: [1×1 rootClass]

その他の回答 (1 件)

Jim Svensson
Jim Svensson 2021 年 8 月 25 日
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.

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by