Hi
I am newbie to Java, I was wondering why do we use static methods.
Thanks
Printable View
Hi
I am newbie to Java, I was wondering why do we use static methods.
Thanks
I mean to say in which screnario do we use static methods.
It would be good if you give some real time example
One of the best reasons is to create a factory class--that is, a class that creates objects of other types.
Now, we can just call CarFactory.create() instead of having that code every time we want a new object.Code:public class CarFactory {
public static Car create() {
Car n = new Car();
n.setModel("some_model.3ds");
n.setWheels(WHEELS_SPINNING);
}
}
This being said, you can make any method object-oriented instead. Instead of this being static, you could declare a new CarFactory object, then have your carFactoryObj.create() method called.
Usually static methods are used to do something globally. Perhaps you have a timer class that manages all time in the application. When you have 50 classes, it's hard to keep track of your timer. Perhaps it's best just to do timeManager.startTimer(), rather than have to store a timeManager object and call it each time. It can save memory in this fashion as well.
It all comes down to personal preference. In my current project, I have several static methods in my main Applet class, which serve as debugging commands and references to objects. For example:
...etcetera. Corresponding to these are many static variables:Code:public static void Pause() { toc.s_ShouldThink = false; }
public static void Resume() { toc.s_ShouldThink = true; }
public static tocCConnection Client() { return toc.s_NetManager.m_Client; }
public static tocSConnection Server() { return toc.s_NetManager.m_Server; }
...and so on.Code:public final static boolean s_Debug = true;
public static Color s_Black = new Color(0,0,0);
public static Color s_White = new Color(255,255,255);
Hope that helps a bit!
PS: Notice that in any snippets I pasted, s_ indicates a static variable while m_ indicates a class member variable.
PPS: Did a bit of Googling for you (though I shouldn't, should let you do it instead), and here are a few other explanations & points of view.
http://www.javaworld.com/javaworld/j...py.html?page=1
http://forums.sun.com/thread.jspa?threadID=562350
http://bytes.com/topic/c-sharp/answe...-static-method
Good luck! :)
Look at the Math class and see if you can figure out why making that a "normal" class that requires objects to be instantiated is a bit pointless.
Otherwise known as utility classes...
While I agree with you, Tolls, in that utility classes are often static (as is my custom math class--Pi(), Rand(), etc), some are not. A custom array class or a string manipulation class, which would both be utilities, would (likely) have a local variable and non-static method access.