MATLAB Object-Oriented Programming

(Joyce) #1

Static Methods


In this section...
“What Are Static Methods” on page 9-32
“Why Define Static Methods” on page 9-32
“Defining Static Methods” on page 9-32
“Calling Static Methods” on page 9-33
“Inheriting Static Methods” on page 9-33

What Are Static Methods


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.

Why Define Static Methods


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.

Defining Static Methods


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;

9 Methods — Defining Class Operations

Free download pdf