How to inherite and intialize object values

1 Ansicht (letzte 30 Tage)
parmeshwar prasad
parmeshwar prasad am 10 Jun. 2019
Bearbeitet: per isakson am 11 Jun. 2019
classdef inputDef
properties
nMatch
end
methods
function obj = inputDef(varargin)
p = inputParser;
p.addParameter('nMatch', 1, @isnumeric);
p.parse(varargin{:});
obj.nMatch = p.Results.nMatch; % Position of the sorting parameters
end
end
end
I have a superclass inputDef which has propety nMatch. I create an object and assign a value as below
>>in = inputDef
>>in.nMatch = 2
How do I inherit inputDef in a another class such that I can get
>> out = outDef(in)
>> out.nMatch = 2
classdef outDef < inputDef
properties
...
end
methods
function obj = outDef(obj1)
obj = obj1
end
end
end
Please give some idea. Thanks in advance

Akzeptierte Antwort

Matt J
Matt J am 10 Jun. 2019
Bearbeitet: Matt J am 10 Jun. 2019
What you've shown would work, but you have to actually assign the properties,
function obj = outDef(obj1)
obj.nMatch = obj1.nMatch;
obj.prop1=_____
obj.prop2=_____
etc...
end

Weitere Antworten (1)

per isakson
per isakson am 10 Jun. 2019
Bearbeitet: per isakson am 11 Jun. 2019
"How do I inherit inputDef in a another class such that [...]"
%%
in = inputDef();
in.nMatch = 2;
%%
out = outDef( in );
%%
out.val.nMatch
outputs
ans =
2
where
classdef inputDef
properties
nMatch = 0;
end
methods
function obj = inputDef(varargin)
p = inputParser;
p.addParameter('nMatch', 1, @isnumeric);
p.parse(varargin{:});
obj.nMatch = p.Results.nMatch; % Position of the sorting parameters
end
end
end
and
classdef outDef
properties
val
end
methods
function this = outDef( obj )
this.val = obj;
end
end
end
That's the standard way, however, to get a bit closer to your proposed code
classdef outDef < inputDef
properties
end
methods
function this = outDef( obj )
this.nMatch = obj.nMatch;
end
end
end
but that looks weird to me. Anyhow, out.nMatch, returns 2
>> out.nMatch
ans =
2
>>

Kategorien

Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by