Static Constructor / Initializer

Actionscript:
  1. package{
  2.    
  3.     public class Lookup{
  4.        
  5.         private static var _random:Array;
  6.         // static initializer
  7.         {
  8.             trace("I am a static initializer for " + Lookup);
  9.             init();
  10.         }
  11.        
  12.         private static function init():void{
  13.              _random = new Array();
  14.              // generate some filler values
  15.              for (var i:int = 0; i<100; i++){
  16.                 _random.push(Math.random() * i);
  17.              }
  18.         }
  19.        
  20.         public static function get random():Array{
  21.             return _random.concat();
  22.         }
  23.     }
  24. }

...and to test out the above class:

Actionscript:
  1. package {
  2.     import flash.display.Sprite;
  3.  
  4.     public class Main extends Sprite{
  5.         public function Main(){
  6.            trace(Lookup.random[50]);
  7.         }
  8.     }
  9. }
  10. /*
  11. outputs:
  12. I am a static initializer for [class Lookup]
  13. 5.4258062043227255
  14. */

The above shows how to use static initializers. I've found this to be very handy... in this case we create an array of random values....

Tomorrow I'll actually post a real class where I make use of this... the Lookup class in this case is really just filler code....

This entry was posted in OOP and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. prad
    Posted April 5, 2012 at 1:49 am | Permalink

    very nice .

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*