How to assign obeject properties to another object
9 views (last 30 days)
Show older comments
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
per isakson
on 26 Jun 2019
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?
Answers (1)
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
0 Comments
See Also
Categories
Find more on Methods 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!