Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

How do u know when to use static?

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello, i was need to know how one would know when to make and identifier static or nonstatic?
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you only want one of them per class (for example, a sum), you would use a static. If you want a new one for each object, you don't want a static variable.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Some languages call static variables "class" variables. I like that name because they store some information about the class in general. Non-static variables store information about one particular object or instance of the class.
I had a class that for debugging needed to identify each new instance by something unique. So here's a mix of static and non static:

There is one instanceCounter variable for the class, no matter how many objects I make. And one idNumber per object so each instance gets its own id number. The numbers helped me keep messages in the console straight.
Another good use for static is to make it easier to share methods and information. If we put critical information in a particular instance of a class, we have to be able to get ahold of that instance to get the information. But if the methods or information are static, we only need to reference the classname.

This time a static variable and a static method made Logger easier to use. Classes with all static stuff are called "utility" classes. Some folks will argue that they are not "good" OO but they work and are commonly accepted.
Was that clearer or more confusing? Ask again if it's not making sense.
reply
    Bookmark Topic Watch Topic
  • New Topic