How to use static factory method?

5 次查看(过去 30 天)
Vincent Schmidt
Vincent Schmidt 2021-7-13
回答: Greg 2024-5-13
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?

回答(1 个)

Greg
Greg 2024-5-13
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.

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by