This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static methods" Watch "Static methods" New topic

Static methods

Aaron Webb

Joined: Aug 16, 2001
Posts: 17
How do I know when to make a method static or create and instance? I am creating a lot of static methods for a utility type of class that I have and I am concerned that multiple requests may step on each other. Is this possible? If the method has one parameter and two requests both pass data in is it possible that the two could get mixed up or something? On the other hand, why would you want to have multiple instances of a method?
John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
Use your OO skills. If the method applies to the class as a whole, keep it static.
If you expect multiple objects in different threads calling some particular static method, and also this particular method manipulates some static member object of its class, perhaps you need to use synchronization.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
An object just holds state, it does not contain any methods. The first time that a class is mentioned, the JVM loads the class by putting all its methods into a method area, then it initializes the static variables and waits for a request to create an instance of the class.
When an actual instance is created the JVM carves out a little segment of memory to hold the current state of the variables for that instance. It does not include any space for method stuff - that is shared.
If you do not need to keep track of variable information for each instance based on the identity of that instance, then do not create any instances. To prevent somebody else from making an instance of it in error you should make the constructor private and don't provide a static "createInstance" method. In addition to prevent someone from extending your class and then creating an instance of THAT you should make your class final.

"JavaRanch, where the deer and the Certified play" - David O'Meara
wood burning stoves
subject: Static methods
Similar Threads
How does Spring framework handle Singleton in its implementation?
How the second client knows the bean is free?
Single object versus multiple