This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Appreciate if someone can explain me the scenarios when static modifier should be used with variables and methods.
Why and when should we make a method static and is there any loophole making a variable or a method static.
You can consider the classes as providing a few special services that objects can't provide
Consider the Utility methods that return some value calculated only from data passed to the method as parameters. You should make such methods static.
Consider Math.max(double a, double b) which is a static method. It does not operate on a single instance; indeed, it would not be good if you say new Math().max(a,b) or even a.max(b).All the data that max uses comes from its two arguments, and not from any owning object
Another important point to consider when you make method static is that you must make sure there
is no chance you’ll want it to behave polymorphically.
When I am developing a complex application that has a GUI, I will often have some kind of a JTextArea in the GUI, at least temporarily, and I will write diagnostics information to this JTextArea from many different parts of the application.
OK you cannot access a non-static variable from a static method, so...
I make my JTextArea static, which ensures that I can write to the JTextArea from both static and nonstatic methods in other parts of the application.
When I no longer need to do diagnostics, I will remove the static modifer, or maybe just remove the JTextARea and all the statements that write to it.
Joined: May 13, 2009
Here is one other reason.
If a method is intended to perform an operation on a primitive data type as opposed to an object, then a static method is often the logical choice, because a non-static method needs an object reference.
For example, the class java.lang.Math contains lots of static methods, such as sqrt( double a). Here, a is a primitive of type double.
The decision of what class to put a static method in is often one of convenience, or logic, as opposed to functionality. For example, you could probably have sqrt in another class, but it is in the Math class because it makes sense to have a single class to house all your static mathematical methods.
p.s. I can see now this is similar to what Muhammed talked about in his post above.