File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When and when not to use static variables?

 
Nikolas Bernadel
Greenhorn
Posts: 10
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say I plan on instantiating one instance of a Car object. Since there's only ever going to be one instance of Car, does it matter if the variables within it are static?
 
Jayesh A Lalwani
Rancher
Pie
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any member variables in singleton objects can cause problems, whether they are static or not. If your singleton Car object is being called by multiple threads, and any of those variables store information that is relevant to one thread, then you will run into concurrency issues
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it does matter. You should, a a general rule, avoid things static unless you have a good reason to make them static. If the fields belong to the object, they belong to the object, and that means not static.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic