tags:

views:

96

answers:

6

How and where should we use a Static modifier for:

1. Field and
2. Method?

For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()

But why is it a good practice?

Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by @duffymo, not in case of Math class).

UPDATE 1:

So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?

+4  A: 

You can think of a 'static' method or field as if it were declared outside the class definition. In other words

  1. There is only one 'copy' of a static field/method.
  2. Static fields/methods cannot access non-static fields/methods.

There are several instances where you would want to make something static.

The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.

Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.

In C#, you can also have static classes which, as you might guess, contain only static members:

public static class MyContainer
{
    private static int _myStatic;

    public static void PrintMe(string someString)
    {
        Console.Out.WriteLine(someString);
        _myStatic++;
    }

    public static int PrintedInstances()
    {
        return _myStatic;
    }
}
Alex
please check my update. Can you give some info about the example method I posted in my question. Which is also a utility method.
zengr
@zengr: Yes, I would make that method static. You can imagine, for example a StringHelper class which encloses all your application-specific String manipulation operations (such as the one performed by that method). In fact, I would make _any_ method static if it does not reference the 'this' keyword; there is no need to create a copy of this method on every object, it is more legible this way, and it is good for clarity of overall design IMO.
Alex
+1  A: 

Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.

Fge
There are perfectly legitimate uses for the static modifier, such as those listed in my answer.
Alex
"they're the same as global variables which should be avoided" -- not if they are final; those appear often as class constants.
Jason S
@alex I haven't thought about that. I guess the use of static fields mostly depends on your way of programming and there probably are perfectly fine situations when to use them (and which are not singletone in any way). Just because I haven't seen them yet doesn't mean they exist or are bad :) For my own interest, could you explain me why you would want to know the total number of instances of an object but no reference to it?
Fge
Sure, let's say I have a game where I create monsters/critters. I would like to keep a simple count of how many critters I've created during the lifetime of the game. IMO the simplest implementation is a static counter variable inside the Monster class.
Alex
@jason As you're saying those are constants which can't be modified by your programm. When thinking of public static fields I think of statics every part of your code can modify. Else I'd refer to them as constants (private static fields again do have their legitimate being too of course).
Fge
@alex thanks :) haven't thought of that. Rather more thought of public static fields (as the given examples were public). Maybe I was a bit too fast with that statement and I should add this (only) applies to public static fields.
Fge
A: 

You can't instantiate an instance of java.lang.Math; there isn't a public constructor.

Try it:

public class MathTest
{
    public static void main(String [] args)
    {
        Math math = new Math();

        System.out.println("math.sqrt(2) = " + math.sqrt(2));
    }
}

Here's what you'll get:

C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
        Math math = new Math();
                    ^
1 error

Tool completed with exit code 1
duffymo
Oops, missed it. But in general, if a method is static, we can anyway access it using an object. So, where does the efficiency of memory come in by using static?
zengr
It's not a matter of memory efficiency; it's about the intent of the class designer.
duffymo
+1  A: 

For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have

public static int age = 25;

Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.

The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.

pilotgallo2
A: 

Static uses less memory since it exists only once per VM.

To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)

Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:

a static field exists only once per JVM. So if you have a simple class (kinda pseudocode):

class Simple {
 static int a;
 int b;
}

and now you make objects with:

Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);

you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in once place in memory.

You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite some uses for this behaviour.

Hope that clears it up a little.

Niko
+1  A: 

Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.

Most of the posts above are similar, but this post might offer some other insight.
When to use Static Modifiers

CitadelCSAlum