Static methods are associated with a class, but not with specific instances of that class. These methods do not perform operations on individual objects of a class and, therefore, do not require an instance of the class as an input argument, like ordinary methods.
Static methods are useful when you do not want to first create an instance of the class before executing some code. For example, you might want to set up the MATLAB® environment or use the static method to calculate data needed to create class instances.
Suppose a class needs a value for pi calculated to particular
tolerances. The class could define its own version of the built-in
for use within the class. This approach maintains the encapsulation
of the class's internal workings, but does not require an instance
of the class to return a value.
To define a method as static, set the methods block
true. For example:
classdef MyClass ... methods(Static) function p = pi(tol) [n d] = rat(pi,tol); p = n/d; end end end
Invoke static methods using the name of the class followed by
.), then the name of the method:
pi method of
the previous section would require this statement:
value = MyClass.pi(.001);
You can also invoke static methods using an instance of the class, like any method:
obj = MyClass; value = obj.pi(.001);
Subclasses can redefine static methods unless the method's
is also set to
true in the superclass.