Static Method vs a normal Method.



  • Hello!

    I've recently encountered a section of the documentation that specifies a static method, versus a regular method.
    While I'm used to methods, I'm unsure of the difference between that and a static method. If someone could inform me or point me in the direction of an example, I'd be quite grateful.

    Thank you in advance. ^^



  • the 'static' keyword in static method refers to that method not allocating memory dynamically, whichmeans that it's not the instance of that class that implements that method, but instead it's implemented only once for the class itself. that's kind of technical so here's an example:

    class MyUtils
    {
    //receives a value, a maximum and a minimum and returns the first value making sure it stays within those bounds
            public static function clamp(value:Int, min:Int, max:Int):Int
    	{
    		if (value < min)
    			return min;
    		else if (value > max)
    			return max;
    		else
    			return value;
    	}
    }
    
    //...
    
    //to use it add this in your PlayState or wherever you want
    var minHP:Int = 0;
    var maxHP:Int = 10;
    var player:FlxSprite;
    
    public function damagePlayer():Void
    {
    player.health -= 20;
    player.health = MyUtils.clamp(player.health, minHP, maxHP);
    trace (player.health); // this will show 0
    }
    

    what's happening here is that you can only access that method through the class, not the instance. you can also have static variables like this

    class Colors
    {
    public static var red:FlxColor = 0xff0000;
    public static var green:FlxColor = 0x00ff00;
    public static var blue:FlxColor = 0x0000ff;
    }
    
    //...
    
    if (player.health <= 0) {
    player.color = Colors.red;
    }
    

    this is very handy for utility methods and variables you want to access freely from wherever in the program, but keeping those methods/variables won't be instanced

    you can use it to store constants like colors, class-wide stats that won't be inherited by other classes, you can make an utility class that has a lot of useful methods for math, string manipulation, etc.

    take a look at the FlxG class for tons of examples of static types being put to good use


Log in to reply
 

Looks like your connection to HaxeFlixel was lost, please wait while we try to reconnect.