• Post Reply Bookmark Topic Watch Topic
  • New Topic

Example for static variable vs instance variables  RSS feed

 
raja singh kumar
Ranch Hand
Posts: 189
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per my understanding, static variable belongs to a class and all instances of that class share that static variable.

Instance variables are ones which belong to an instance.

Can someone please post a practical meaningful example where I would use a static variable and when I would use an instance variable?
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some people would say there is no such thing as a static variable, and that static fields shou‍ld be reserved for constants. There are two public static constants in that class. They will be implemented something like this:-Actually, the largest part of each implementation is the documentation comment.
Because those fields are static, there is exactly one copy of each, irrespective of how many instances of the class there are. If there is one instance, there is one field. If there are one million instances, there is one field. If there is no instance, there is one field. The latter is the actual state of affairs; that class is uninstantiable, so there are no instances.
 
Sergiu Dobozi
Ranch Hand
Posts: 107
2
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static variable value can be changed by an object and all the other objects will see the changed value.
If we change it by deleting the static in front of it, the variable value can be changed by an object and all the other objects will still see the same original value. So the field now refers to two values. It's not so STATIC anymore 
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sergiu Dobozi wrote:. . . If we change it by deleting the static in front of it, the variable value can be changed by an object and all the other objects will still see the same original value. So the field now refers to two values. . . .
Really? That looks wrong to me. If you change the variable from static to instance, you will have to recompile the code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!