It's not a secret anymore!
The moose likes Beginning Java and the fly likes Static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static" Watch "Static" New topic


aathu aathu

Joined: Feb 06, 2005
Posts: 1

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

Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Subhash Bhushan C
Ranch Hand

Joined: Jan 27, 2005
Posts: 106
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.

    Regards,<br />Subhash Bhushan.
    Layne Lund
    Ranch Hand

    Joined: Dec 06, 2001
    Posts: 3061
    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.


    Java API Documentation
    The Java Tutorial
    It is sorta covered in the JavaRanch Style Guide.
    subject: Static
    It's not a secret anymore!