How can I create an inherit class based on variable value?
Show older comments
Hi,
I've defined multiple classes (class1, class2, class3...) which all inherit from one class (class0):
classdef class0 ...
classdef class1 < class0 ...
classdef class2 < class0 ...
classdef class3 < class0 ...
and I have a variable 'index', which is 1 or 2 or 3. I'm trying to create a object whose class type is based on this index. For example, if index is 1, I want a object of class1. So far I can acheive this by calling a function like in the following code:
function test = create_class_obj(index)
switch index
case 1
test = class1();
case 2
test = class2();
case 3
test = class3();
end
end
Is there an elegant way to encode this into the constructor of class0? So that I can do the following:
test = class0(index);
Thanks.
Josh
Accepted Answer
More Answers (1)
classdef baseClass < handle
methods
function baseClass(index)
...
end
end
...
classdef class0 < baseClass
methods
function class0(index)
% explicitly call the superclass constructor with argument
@obj.baseClass(index)
end
...
Categories
Find more on Extend Testing Frameworks 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!