MATLAB: Property validation in subclass

inheritanceooppropertysubclassvalidation

Hello everyone, i am new to the OOP in Matlab.
I have a superclass SimpleList with the property set, which is an array with any kind of data in it.
classdef SimpleList < handle
% SimpleList
properties
set(:,1)
end
methods
.
.
.
end
end
And a subclass ObjList, where the array should only contain objects of a specific class
classdef ObjList < SimpleList
% ObjectList
properties
end
methods
.
.
.
end
end
My Question is: How do i validate the property in ObjList?
Thanks in advance!

Best Answer

Note: I would recommeng giving a name other than set to your property. That name is already overloaded enough by matlab.
You can create a property validation function in the class that define the property using the syntax (for handle classes):
function set.propertyname(object, valuetoset)
%validation code
end
with your property name this would be
function set.set(this, value) %See why you should rename the property?
if ~strcmp(class(value), somevalidclass)
error('invalid class supplied to set');
end
this.set = value;
end
However, as I said, this property set method must be implemented in the class that defines the property, that is your base class, not the derived class. The workaround is from the set method to call another method that does the validation and is overridden by the derived class:
classdef SimpleList < handle
properties
set;
end
methods
function set.set(this, value)
isok = this.validateset(value);
if ~isok
error('invalid type of variable for set property)
end
this.set = value; %DO NOT set the value is a subfunction or you'll get infinite recursion
end
end
methods (Access = protected)
function isok = validateset(this, value)
isok = true;
end
end
end
classdef ObjList < SimpleList
methods (Access = protected)
function isok = validateset(this, value)
isok = strcmp(class(value), 'double');
end
end
end