I have been doing programming type stuff since middle school now (nine years, whoa) , with my first object-oriented experiences in high school Java class. I remember talking about static variables then (maybe in college too, I don't know). However, last Thursday I was writing some Actionscript code for my research project and realized I was mindlessly typing "public static var" in front of all my declarations, and that I really didn't know what "static" meant. So, I checked to see who was online, and my friend Lane was, and I asked him what static variables are. He explained it this way:
class Orange{
public var count;
public static var staticCount;
Orange(){
count++;
staticCount++;
}
}
...
var valencia = new Orange();
var navel = new Orange();
So, what will valencia.staticCount be? What will navel.staticCount be? What about valencia.count and navel.count?
Turns out that static variables are shared across all instances of a class. So, either of the staticCounts will be 2 after each instance is created (since each time the instance is created, the class increments staticCount), while each count will be 1, since the constructor also increments the non-static, unshared variable as well.
After I asked that question I figured out that a whole bunch of my program's bugs had to do with me declaring static variables where they should not be.
I don't know, it seems like several people I've talked to don't (or didn't) fully understand static variables either, but it's something really helpful to know.
Saturday, June 28, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment