Validate property is a subclass of an abstract class
14 ビュー (過去 30 日間)
I've just upgraded from 2018b to 2020a and some of my code has stopped working. With release 2018b the following code did not throw an error. The idea is that myProperty must always be a subclass of myAbstractClass.
When I attempt to use myClass in release 2020a I get the following complaint: "Error defining property 'myProperty' of class 'myClass'. Class myAbstractClass is abstract. Specify a default value for property myProperty."
Having read the documentation carefully (https://uk.mathworks.com/help/matlab/matlab_oop/property-size-and-class-validation.html#bvklfs7-1) I can see that Matlab is attempting to assign a default value to myProperty which is an empty instance of myAbstractClass. At this point the code fails because it is not possible to instantiate an abstract class. Presumably the default value was assigned differently in 2018b or the checks were less rigerous. Anyway, I've now got a codebase which doesn't work and needs fixing.
Obviously I could write my own property validation function to get the behaviour I require, or I could do validation in the setter. I've used the same trick in other places in the code, so ideally I don't want to spend ages writing custom property validation functions or modifying setters. Is there an elegant way to deal with this? Something like a mustBeClass validaiton function?
回答 (1 件)
Tim Johns 2020 年 9 月 2 日
I can see that Matlab is attempting to assign a default value to myProperty which is an empty instance of myAbstractClass. At this point the code fails because it is not possible to instantiate an abstract class.
Correct. So what you need to do is specify a default property value that is a concrete class:
myProperty(1,1) MyAbstractClass = MyConcreteClass()
Where for example:
classdef (Abstract) MyAbstractClass
classdef MyConcreteClass < MyAbstractClass