Using Static Methods

 <  Day Day Up  >  

Using Static Methods

It is possible to access class fields and class methods without creating an instance or an object of a class. You can do so by using the static key word. By declaring a method with the static key word, the method becomes associated with the class itself, not with instances of the class. In a sense, static or "class" fields and methods are global variables and methods that we can touch using the class name . The major advantage of static methods is that each object does not have to use memory in the Flash Player. A disadvantage is that static methods are not aware of properties in an object instance because they are only associated with a class. Static methods are not useful when you need to know about properties and methods in an object.

You call static methods by actually referencing the class name, as in the following example; there is no need to create an object instance from the class.

 trace (Math.Random()); 

We can add custom static methods to our own classes. For example, in the Employee class, where employer is a static method, it makes sense to retrieve that information using a static method. If there are multiple employees , this will conserve memory because it will be stored with the class and not each object.

 class Employee {       private var firstName:String;       private var lastName:String;       private static var company:String = "Tapper.net Consulting";       public static function getCompany():String{             return Employee.company;       }       function getFirstName():String{             return this.firstName;       } } 
 <  Day Day Up  >  


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net