I ran into a problem with setting the Parent and Children of a user-defined class, and I ended up writing my own methods that seem a lot more complicated than they need to be. I'm wondering if there is inheritable behavior for this?
classdef superClass properties Parent = []; Children = []; end methods function obj = superClass( varargin ) % Set the parent, children given input.
p = inputParser; addOptional( p, 'Parent', obj.Parent ); addOptional( p, 'Children', obj.Children ); parse( p, varargin{:} ); obj.setParent( p.Results.Parent ); obj.setChildren( p.Results.Children ); end function setParent( obj, otherObj ) % Behaviour of this function should probably be a lot more nuanced than this:
obj.Parent = otherObj; end function setChildren( obj, otherObj ) % Probably don't want to have multiple references to the same Child?
obj.Children = vertcat( otherObj, obj.Children ); end endendclassdef subClass < superClass properties end methods function obj = subClass( varargin ) p = inputParser; addOptional( p, 'Parent', obj.Parent ); addOptional( p, 'Children', obj.Children ); parse( p, varargin{:} ); % Set myClass instance's Parent, Children given input AND concurrently
% set superClass' instance's Children to include this new subClass object.
obj.setParent( p.Results.Parent ); % This needs to be overridden?
obj.setChildren( p.Results.Children ); % This needs to be overridden? end endend
I want these classes to be able to make the following code error-free:
dad = superClass();son = subClass( 'Parent', dad );if ismember( dad, son.Parent ) disp( 'hooray' )else disp( 'booooo' )end
Best Answer