How to assign obeject properties to another object
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
per isakson
le 26 Juin 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?
Réponses (1)
Matt J
le 24 Juin 2019
Modifié(e) : Matt J
le 26 Juin 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 commentaires
Voir également
Catégories
En savoir plus sur Methods dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!