What's the difference between a public static method and a public method? Why would you use a public static method?
static methods are methods that a not specific to any instance of a class (object) they are methods that are not allowed to contain this references and you can access them through the class directly (not the object instances)
The methods of the Math class are static. So, in doing
Math.round(average)
the Math class itself is unchanged by what you've done - it only returns a value or acts upon the value you pass.
So - static methods are useful for utilities. Things like
StringUtils.removeWhitespaceFrom(textContent:String):String
or
BrowserUtils.openInNewWindow(url:String):void
It's very unusual that you'd use a static method for anything else. Don't use statics like 'getInstance()' to create Singletons - look into a framework for dependency injection instead.
To make your concept clear, Suppose if you want to know how many times your class has been instantiated, you will be using static variable counter in your class constuctor, each time your object is created.
Then you have to use static method to access this data else you can declare your variable public or default and access it with class name but that violates the OOP principals. here is the little example
public class CAR {
private static var Counter:int=0;
private function CAR(){ Counter++; }
public static function ReturnTotalCarInstances():int { return Counter; }
}
Static variables have their benefit thats why it is provided in most programming languages. Counting instances is the small use of static variable. They are used in much bigger scope. The main point is it is used to share data globally among all objects of Class.
Static methods can be used as overloaded constructors. ActionScript doesn't have function overloading, so sometimes I'm writing something like:
public class Foo {
public static function fromBar(bar:Bar):Foo { var foo:Foo = new Foo(); ... //initializing foo object from bar return foo; } public static function fromBaz(baz:Baz):Foo { var foo:Foo = new Foo(); ... //initializing foo object from baz return foo; }
}