Static methods are associated with a class, but not with specific instances of that class. These methods do not require an object of the class as an input argument. Therefore, you can call static methods without creating an object of the class.
Static methods are useful when you do not want to create an instance of the class before executing some code. For example, suppose you want to set up the MATLAB® environment or use the static method to calculate data required to create class instances.
Suppose that a class needs a value for pi calculated to particular tolerances. The class could define its own version of the built-in
pi function 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
Static attribute to
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 dot (
.), then the name of the method:
pi method of
MyClass in 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
Sealed attribute is also set to
true in the superclass.