Public static methods vs public methods

redconservatory picture redconservatory · Sep 30, 2010 · Viewed 10.2k times · Source

What's the difference between a public static method and a public method? Why would you use a public static method?

Answer

Stray picture Stray · Sep 30, 2010

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.