Static Methods

Why Define Static Methods

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 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.

Defining a Static Method

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

Update Graphs Using Events and Listeners provides an example that uses a static method to create a set of objects representing graphs.

Calling Static Methods

Invoke static methods using the name of the class followed by dot (.), then the name of the method:

classname.staticMethodName(args,...)

Calling the 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);

createViews static methodcreateViews static method provides an example of a static method.

Inheriting Static Methods

Subclasses can redefine static methods unless the method's Sealed attribute is also set to true in the superclass.

Was this topic helpful?