[squeak-dev] Class variables

Randal L. Schwartz merlyn at stonehenge.com
Mon Jul 14 14:42:15 UTC 2008


>>>>> "Alexandre" == Bergel, Alexandre <bergel at iam.unibe.ch> writes:

Alexandre> Class variables are accessible within the instance and class sides.
Alexandre> class instance variables are accessible only within the class
Alexandre> instance side.

Continuing on that, suppose you have Parent and Child classes, with the Child
class being a subclass of Parent.

If you define 'Home' as a class variable of Parent, you can use Home in both
Parent and Child class *and* instance methods, and it'll refer to the single
object defined in Parent class.  (Class variables are always capitalized.)

If you define 'office' as a class-instance variable of the Parent class, you
can use it in Parent class methods only, not Parent instance methods.
And, the Child class methods can also "use it", but they're referring to
their own independent class-instance variable unique to the Child class.

In other words, a class-instance variable is to a class, what an instance
variable is to an instance: unique to the object.  A class variable, on the
other hand, is a bit like a global, but visible only to a class and its
subclasses in all class and instance methods.  As with any broad-scoped
variable, use class variables only when needed, since it makes subclassing
trickier and scope pollution and "action at a distance" more likely.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion



More information about the Squeak-dev mailing list