How to use static factory method?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Greg
am 13 Mai 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 Kommentare
Siehe auch
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!