How to assign obeject properties to another object

10 visualizzazioni (ultimi 30 giorni)
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 Commento
per isakson
per isakson il 26 Giu 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?

Accedi per commentare.

Risposte (1)

Matt J
Matt J il 24 Giu 2019
Modificato: Matt J il 26 Giu 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

Categorie

Scopri di più su Methods in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by