MATLAB: Calling one method from a Static method

callbackMATLABmethodsoopstatic

Hello,
Here is the class definition:
classdef first < handle
methods (Static)
function hello
obj_first.bye
end
end
methods
function bye(obj)
disp('that works')
end
end
end
Here are my commands:
>> obj_first=first;
>> obj_first.bye
that works
>> obj_first.hello
Undefined variable "obj_first" or class "obj_first.bye".
Error in first.hello (line 4)
obj_first.bye
>>
Can you please help me?
Thank you very much

Best Answer

Static methods apply to the class itself rather than instances (objects) of the class.You normally call such a method with classname.methodname, (i.e. in your case with first.hello). Matlab allows to call static methods from instances just so you don't have to determine the class of the object yourself, but other than determining which class the method belongs to, the object itself plays no role in the invocation of a static method. It is not passed to the method.
I don't understand why you thought your code would work. There's no obj_first in the scope of the static method, and even if somehow you made it able to access the variable from another workspace, there's no guarantee that such a variable exists.
More importantly, I don't understand what you're trying to achieve with your static method here. Can you explain what problem you're trying to solve?
One simple way to fix your code is to change the static method, so it takes an input:
function hello(some_obj)
some_obj.bye;
end
and you would then call it with:
obj_first.hello(obj_first)
But the whole lot would be pointless. You may as wall call the object method directly.
Another way to solve this, would be to create a singleton obj_first within the class but I've no idea if that's what you meant to do:
classdef first < handle
methods (Static)
function hello
obj_first = getsingleton();
obj_first.bye();
end
function obj_first = getsingleton()
persistent obj_first;
if isempty(obj_first)
obj_first = first();
end
end
end
methods
function bye(obj)
disp('that works')
end
end
end
>>obj_first = first.getsingleton;
>>obj2 = first();
>>first.hello();