I think the easy way to remember what static means is to think of the address of the variable.
A static variable is given one address and then it is not changed (it is statically allocated, not allocated on the stack or in an object). In this way it is like a shared property but has the private scope of a local variable. It is a shame that the word static is used since I think it is a bit confusing. Malcolm On Feb 27, 2007, at 5:25 PM, Joe Huber wrote: > At 2:46 PM -0800 2/27/07, Tim Hare wrote: >> A word of caution regarding static variables. ... static variables >> are global to all instances of that class. > > Tim has a very good point. Yes, this is a very important and often > overlooked issue, and can lead to some hard to find bugs. > > STATIC is an odd mix of both Local and Global scope. A STATIC > variable can only be accessed from within the method where it's > defined. Seems pretty local in scope right? > > Well that same exact STATIC variable is used by ALL instances of that > class. Even if you have 100 instances of that class there is still > only one copy of that STATIC variable. So what happens to that STATIC > variable in one instance DOES AFFECT the value of that variable in > ALL other instances. That's a pretty global effect. > > A STATIC variable has two important traits vs a normal local variable: > > - The STATIC variable retains its value across multiple calls to > that method > ie Persistence > > - The SAME STATIC variable is shared among all instance of that > class > ie Shared > > This is a very nice capability when you need it. > > But like Tim says, be very careful if you're using a STATIC to get > persistence in a method, because it also comes along with being > SHARED among all instances which can be a very rude surprise and can > cause apparently 'local' variables to change unexpectedly. > > Remember that eventhough a STATIC is declared within a method it is > NOT local to that instance, it is SHARED by all instances. > > Regards, > Joe Huber > > PS I know I bent the name space terms a little bit but I think it's > the best way to describe what actually happens and to make statics > simpler to remember. > _______________________________________________ > Unsubscribe or switch delivery mode: > <http://www.realsoftware.com/support/listmanager/> > > Search the archives: > <http://support.realsoftware.com/listarchives/lists.html> _______________________________________________ Unsubscribe or switch delivery mode: <http://www.realsoftware.com/support/listmanager/> Search the archives: <http://support.realsoftware.com/listarchives/lists.html>
