How to assign obeject properties to another object

Hi, I have a superClass as follows:
classdef superClass < handle
properties
a = 0;
b = []
end
methods
function obj = superClass(varargin)
if (nargin>0)
p = inputParser;
p.addParameter('a', 0, @isnumeric);
p.addParameter('b', 0, @isnumeric);
p.parse(varargin{:});
obj.a = p.Results.a;
obj.b = p.Results.b;
end
end
end
end
which gives:
>> obj1=superClass('a',3,'b',5)
obj1 =
superClass with properties:
a: 3
b: 5
How do I create another object obj2 using a subclass such that
obj2 = subclass(obj1, 'c' , 7)
obj2 =
subClass with properties:
a: 3
b: 5
c: 7
Thank you, in advance.

1 Comment

The names SuperClass and SubClass make me think about inheritance. However, the signature subclass(obj1,'c',7) make me think about composition. See Composition over inheritance.
The output
obj2 =
subClass with properties:
a: 3
b: 5
c: 7
speaks for inheritance.
Or are you intending something else?

Sign in to comment.

Answers (1)

Matt J
Matt J on 24 Jun 2019
Edited: Matt J on 26 Jun 2019
As long as the properties are not Dependent, you can use the attached routine to assist with the property-copying in the subclass constructor,
classdef subclass < superclass
methods
function obj=subclass(obj1,varargin)
obj=copyprops(obj1,obj);
if (nargin>1)
p = inputParser;
p.addParameter('c', 0, @isnumeric);
p.parse(varargin{:});
obj=copyprops(p,obj);
end
end
end
end

Categories

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

Asked:

on 24 Jun 2019

Edited:

on 26 Jun 2019

Community Treasure Hunt

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

Start Hunting!