This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static methods

 
Aaron Webb
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aaron,
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"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aaron,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic