Advanced Points on Classes
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Roadmap
- Sharing state between instances of a class
- Instance variables of classes
- Class initialization
Roadmap
- Sharing state between instances of a class
- Instance variables of classes
- Class initialization
Sharing State?
How do you share state between instances of a class?
- in Java, an "instance" variable can be
static
- in Pharo, we use class variables
Class Variables
- shared by the instances of the class and subclasses
- accessible from instance and class methods
- start with an uppercase letter
Class Variable Access
Class Variable Access
Roadmap
- Sharing state between instances of a class
- Instance variables of classes
- Class initialization
Class Instance Variables
A class can have instance variables like any object
- a class is an instance of a class (its metaclass)
- a metaclass can specify class instance variables
- accessible from class methods only
- start with a lowercase letter
No Sharing with Class Instance Variables
Each instance has a different value for cachePackages
Singleton Design Pattern
- Intent: Enforce that a class has only one instance
- A solution: Keep the instance in a variable of the class
Singleton with a Class Instance Variable
Consequence:
- each subclass has its own value for
uniqueInstance
- each subclass of
WebServer
has its own singleton
Singleton with a Class Variable
Consequence:
- only one singleton for the complete class hierarchy
- class variable values are shared
Roadmap
- Sharing state between instances of a class
- Instance variables of classes
- Class initialization
Class Initialization
- Everything is an object
- An object is initialized at creation time
- Classes are objects too
How and when are classes initialized?
Class Initialization
A class is initialized
- at load time after its methods are loaded
- or explicitly by the programmer:
Color Initialization
Warning
- don't write
super initialize
in a class initialize
method
- this will initialize superclasses that are already initialized
What You Should Know
- state is shared between instances through class variables
- a class can store values in class instance variables
- a class is initialized through the class method
initialize
/