• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static

 
aathu aathu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would like to know the advantage and disadvantage of static methods.

Thanks,
aathu
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Their advantage is that you don't need an object to call them; disadvantage: they aren't polymorphic (and therefore make a more rigid design).

I mostly use them for creation methods (when a constructor would become too complex or wouldn't communicate well enough) and for "foreign methods" - methods I can't put on the class they'd belong to, because I can't change their source.
 
Subhash Bhushan C
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two instances where a static method makes more sense than a normal method:

  • When the method is not linked to an instance of the class in any way. An example would be a method which always returns a random number. This need not be associated with any instance of the class, meaning that it does not depend on the state of an object. So might as well have one instance of the method, with the class, rather than have one with every object.
  • When you need to keep track of the number of instances instantiated from a particular class. In this case, static variables can be used, along with a static method to create an object of the class.(This is the same case as what Ilja mentioned before.)

  • And please take a look at our naming policy.
     
    Layne Lund
    Ranch Hand
    Posts: 3061
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    If you are interested, look at the Java API for examples where static methods are used. The example that comes to mind is the Math class. The methods it provides are typically used to calculate the value of mathematical function. It really wouldn't make much sense to require an instance of the Math class to call these functions.

    Layne
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic