Static vs Instance Variables: Difference?

user2971033 picture user2971033 · Jan 18, 2014 · Viewed 98.2k times · Source

What is the difference between a static and instance variable. The following sentence is what I cant get:

In certain cases, only one copy of a particular variable should be shared by all objects of a class- here a static variable is used.
A static variable represents class wide info.All objects of a class share the same data.

I thought that instance vars were used class wide whereas static variables only had scope within their own methods?

Answer

Stefano Sanfilippo picture Stefano Sanfilippo · Jan 18, 2014

In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.

Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:

  1. class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static method can only access static attributes, but think twice before trying this.

Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.