Static Methods and Properties

By default, properties and methods are instance properties and methods, which means they are defined for each instance of the class. If the Example class defines a _id property and a getId( ) method then, by default, each instance of Example has its own _id property and getId( ) method.

However, there are cases in which you want the property or method to be associated with the class itself rather than with instances of the class. That means that no matter how many instances of the class there may be, there is just one property or method. Such properties and methods are called static properties and methods.

There are examples of static properties and methods in several of the intrinsic Flash Player classes. For example, the Math class defines a round( ) method. The round( ) method is static and is, therefore, accessible directly from the class:

trace(Math.round(1.2345));

Note that you don't have to create a new Math object to use its methods; you simply call the methods as properties of the class itself, such as Math.random( ), Math.round( ), and so on.

You can declare a property or method as static using the static attribute. The static attribute is always used in combination with the public, private, protected, or internal attribute.

One common and important use of static properties and methods is the Singleton design pattern, whereby a class has a single managed instance. Singleton classes have a private static property that stores the one instance of the class as well as a public static method that allows access to the one instance.

Post A Comment

Anti-Spam Quiz: