[Newbies] class variable vs class instance variable uses

Göran Krampe goran at krampe.se
Wed Aug 5 07:15:53 UTC 2009


Hi!

Or to rephrase it once more:

A class variable is like a global, but only accessible from the class, 
its instances and from subclasses and their instances. Kinda like a 
"scoped global". A bit similar to a "static" variable in say Java - 
"There Can Be Only One" :)

A class instance variable is a much more "natural" thing really. It is 
simply an instance variable in the class *itself*. Remember that classes 
are real objects in Smalltalk and thus can have instance variables as 
well as behavior.

Also, this means we naturally have "inheritance on the class side" which 
means that just like class side methods are inherited by subclasses 
(unlike static methods in Java which really are just like C functions) 
these class instance variables are also inherited by subclasses. But 
remember - inheritance doesn't mean that the subclasses will "see" the 
variable of the superclass - it means that the subclasses will have 
their *own* such instance variable, which again is natural since each 
class is a different object.

And also, naturally, class instance variables are not accessible from 
the instances of the class!

So class instance variables behave just like regular instance variables 
- but *in the class itself*. Btw, if you type a class name, select it, 
and press alt-i you get an inspector on the class object and you can see 
all its instance variables, as you can see there is a whole bunch.

Yes, this was a much longer explanation but might have cleared up some 
question marks still lingering. :)

regards, Göran



More information about the Beginners mailing list