Is there inheritable behavior (or a Mixin) for setting/getting the 'Parent' and 'Children' properties of a custom class?

3 views (last 30 days)
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
end
end
classdef 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
end
end
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

Accepted Answer

per isakson
per isakson on 6 Dec 2019
Edited: per isakson on 6 Dec 2019
"make the following code error-free"
There is a problem regarding handle or value class. In the code it's assumed that superClass is a handle-class, however it's defined as a value-class. I assume you intended it as a handle-class and replace
classdef superClass
by
classdef superClass < handle
Furthermore, I replace subClass by
classdef subClass < superClass
properties
end
methods
function obj = subClass( varargin )
obj@superClass( varargin{:} );
end
end
end
(propably not needed)
Now
%%
dad = superClass();
son = subClass( 'Parent', dad );
%%
if ismember( dad, son.Parent )
disp( 'hooray' )
else
disp( 'booooo' )
end
prints hooray in the Command Window
"there is inheritable behavior for this?" AFAIK: No

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!