Clear Filters
Clear Filters

How to use static factory method?

3 views (last 30 days)
Vincent Schmidt
Vincent Schmidt on 13 Jul 2021
Answered: Greg on 13 May 2024
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?

Answers (1)

Greg
Greg on 13 May 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.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!