Pass class selection to function
3 views (last 30 days)
Show older comments
Hi everyone.
I have a question on classes. Can I hand over a Classname to a function, so that the function uses that specific Class?
I could use strings and a switch statement, but is there a simpler way?
See the example below for details on how i want it to work.
Imagine i have a superclass Employes. Employes has an abstract function Setup.
classdef Employe <handle
properties (Abstract)
name;
end
methods (Abstract)
Setup(Obj,Name,arg)
end
end
I have two subclasses to Employe, one being Salesman, the other Developer. Both have a custom Setup function.
classdef Salesman < Employe
properties
sold=0;
end
methods
function Setup(Obj,Name,arg)
arguments
Obj Salesman;
Name string;
arg.sold int =0;
end
Obj.name=Name
Obj.sold=arg.sold;
end
end
end
classdef Developer < Employe
properties
language="";
end
methods
function Setup(Obj,Name,arg)
arguments
Obj Salesman;
Name string;
arg.language string ="";
end
Obj.name=Name
Obj.language=arg.language;
end
end
end
Now i want to setup my staff in a serperate function that creates an array of one kind of employes.
function Staff=CreateStaffArray(EmployeType,length)
Staff=EmployeType.empty(length,1)
%followed by some filling of Staff
.
.
.
end
Where EmployeType would either be Developer or Salesman.
Is there a way to do this?
0 Comments
Accepted Answer
Matt J
on 16 Aug 2021
Edited: Matt J
on 16 Aug 2021
It seems to me your setup functions should be converted to class constructors that accept zero input arguments. There is no point having argument validation if you are just going to be assigning the values to properties. You can do the validation in the property defintion blocks instead.
classdef Employe <handle
properties (Abstract)
name String;
end
end
classdef Salesman < Employee
properties
sold=0;
end
methods
function Obj=Salesman(Name,sold)
if ~nargin, return; end
Obj.name=Name;
Obj.sold=sold;
end
end
end
classdef Developer < Employee
properties
language String ="";
end
methods
function Obj=Developer(Name,language)
if ~nargin, return; end
Obj.name=Name;
Obj.language=language;
end
end
end
Once you've done this, you could simply use feval() to invoke the constructor that you want:
function Staff=CreateStaffArray(EmployeeType,N)
Staff(N)=feval(EmployeeType);
%followed by some filling of Staff
.
.
.
end
2 Comments
Matt J
on 19 Aug 2021
The simplest way to fix that is to make Employee a value class (instead of handle). Otherwise, you must use a loop and construct each Staff(i) individually.
More Answers (0)
See Also
Categories
Find more on Solver-Based Optimization Problem Setup 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!