• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static Variables/Methods  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I get the basic gist of static variables/methods, you know, in that when a method or variable is declared 'static' that means it belongs to that class and therefore I can simply just refer to it instead of having to create an object so that I can call to a non-static method.

However, where static variables are concerned, if by declaring a variable static we are only allotting the program a single copy of the variable (for instance, static int myVariable), does that mean that every time 'myVariable' is referenced (if I reference it more than once in my program, assuming that I can) the previous data is overwritten?

Or can you not even do that?
 
Saloon Keeper
Posts: 3330
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cookie Nguyen wrote:So I get the basic gist of static variables/methods, you know, in that when a method or variable is declared 'static' that means it belongs to that class and therefore I can simply just refer to it instead of having to create an object so that I can call to a non-static method.

However, where static variables are concerned, if by declaring a variable static we are only allotting the program a single copy of the variable (for instance, static int myVariable), does that mean that every time 'myVariable' is referenced (if I reference it more than once in my program, assuming that I can) the previous data is overwritten?

Or can you not even do that?
If it is a private static it can be referenced anywhere in the class. If it is public static it can also be referenced outside of the class.

When you reference it to get its value then you'll be getting the same value that would be available to other places you may reference it. If you assign a new value to the reference then all other places that get its value will now get the new value.
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . .  and welcome to the Ranch

Remember that it is normal to create objects, and that means instance variables. You shou‍ld always regard anything static as an exception to the normal practice.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!