| MATLAB® | ![]() |
| On this page… |
|---|
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.
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
Example — Using Events to Update Graphs provides an example that uses a static method to create a set of objects representing graphs.
You invoke a static method using the name of the class followed by dot, and then the name of the method:
classname.staticMethodName(args,...)
Calling the pi method discussed above would require this statement:
value = myClass.pi(.001);
createViews static method provides an example of a static method.
Subclasses can redefine static methods unless the method's Sealed attribute is also set to true in the superclass.
![]() | Creating Object Arrays | Overloading MATLAB® Functions | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |