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

3 次查看(过去 30 天)
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

采纳的回答

per isakson
per isakson 2019-12-6
编辑:per isakson 2019-12-6
"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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by