How to use static factory method?
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have following class definition under +mypackage\MyClass.m
classdef MyClass
properties
num
end
methods (Static)
function obj = with_five()
obj = MyClass(5);
end
end
methods
function obj = MyClass(num)
obj.num = num;
end
end
end
I use with_five() as a static factory method.
Following script should create two objects.
import mypackage.MyClass
class_test1 = MyClass(5);
class_test2 = MyClass.with_five();
class_test1 has been created.
For class_test2 it says:
Error using MyClass.with_five
Method 'with_five' is not defined for class 'MyClass' or is removed from MATLAB's search path.
Error in Testpackage (line 4)
class_test2 = MyClass.with_five();
When I put MyClass.m outside of a package folder and remove the "import" statement, it works.
What am I doing wrong?
0 comentarios
Respuestas (1)
Greg
el 13 de Mayo de 2024
Old question, but maybe others have seen this and wondered the same thing. Fairly simple answer.
In your factory method, you do not call out the namespace:
obj = MyClass(5);
Needs to be:
obj = mypackage.MyClass(5);
The import is in your test script, not your class. Import statements are extremely localized, so the factory method does not know about a MyClass, only a mypackage.MyClass.
0 comentarios
Ver también
Categorías
Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!