Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do u know when to use static?

 
Sally Curtis
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, i was need to know how one would know when to make and identifier static or nonstatic?
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • 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.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic