SlideShare uma empresa Scribd logo
1 de 51
S.Ducasse 1
7. Understanding Metaclasses
S.Ducasse 2
Roadmap
• Metaclasses in 7 points
• Indexed Classes
• Class InstanceVariables
• ClassVariables
• Pool Dictionaries
S.Ducasse 3
Metaclasses in 7 points
1. Every object is an instance of a class
2. Every class eventually inherits from Object
3. Every class is an instance of a metaclass
4. The metaclass hierarchy parallels the class hierarchy
5. Every metaclass inherits from Class and Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
Adapted from Goldberg & Robson, Smalltalk-80 — The Language
S.Ducasse 4
Metaclasses in 7 points
1.Every object is an instance of a class
2. Every class eventually inherits from Object
3. Every class is an instance of a metaclass
4. The metaclass hierarchy parallels the class hierarchy
5. Every metaclass inherits from Class and Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 5
1. Every object is an instance of a
class
S.Ducasse 6
Metaclasses in 7 points
1. Every object is an instance of a class
2.Every class eventually inherits from Object
3. Every class is an instance of a metaclass
4. The metaclass hierarchy parallels the class hierarchy
5. Every metaclass inherits from Class and Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 7
2. Every class inherits from Object
Every object is-an Object =
The class of every object
ultimately inherits from Object
S.Ducasse 8
The Meaning of is-a
• When an object receives a message, the method is
looked up in the method dictionary of its class, and, if
necessary, its superclasses, up to Object
S.Ducasse 9
Responsibilities of Object
• Object
• represents the common object behavior
• error-handling, halting …
• all classes should inherit ultimately from Object
S.Ducasse 10
Metaclasses in 7 points
1. Every object is an instance of a class
2. Every class eventually inherits from Object
3.Every class is an instance of a metaclass
4. The metaclass hierarchy parallels the class hierarchy
5. Every metaclass inherits from Class and Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 11
3. Every class is an instance of a metaclass
• Classes are objects too!
• Every class X is the unique instance of its metaclass,
called X class
S.Ducasse 12
Metaclasses are implicit
• There are no explicit metaclasses
• Metaclasses are created implicitly when classes are
created
• No sharing of metaclasses (unique metaclass per class)
S.Ducasse 13
Metaclasses by Example
Square allSubclassesSquare allSubclasses
Snake allSubclassesSnake allSubclasses
Snake allInstancesSnake allInstances
Snake instVarNamesSnake instVarNames
Snake back: 5Snake back: 5
Snake selectorsSnake selectors
Snake canUnderstand: #newSnake canUnderstand: #new
Snake canUnderstand: #setBack:Snake canUnderstand: #setBack:
S.Ducasse 14
Metaclasses in 7 points
1. Every object is an instance of a class
2. Every class eventually inherits from Object
3. Every class is an instance of a metaclass
4.The metaclass hierarchy parallels the
class hierarchy
5. Every metaclass inherits from Class and Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 15
4.The metaclass hierarchy
parallels the class hierarchy
S.Ducasse 16
Uniformity between Classes and Objects
• Classes are objects too, so …
• Everything that holds for objects holds for classes as
well
• Same method lookup strategy
• Look up in the method dictionary of the metaclass
S.Ducasse 17
About the Buttons
S.Ducasse 18
Metaclasses in 7 points
1. Every object is an instance of a class
2. Every class eventually inherits from Object
3. Every class is an instance of a metaclass
4. The metaclass hierarchy parallels the class hierarchy
5.Every metaclass inherits from Class and
Behavior
6. Every metaclass is an instance of Metaclass
7. The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 19
5. Every metaclass inherits from Class and
Behavior
• Every class is-a Class =
The metaclass of every
class inherits from Class
S.Ducasse 20
Where is new defined?
S.Ducasse 21
Responsibilities of Behavior
Behavior
Minimum state necessary for objects that have instances.
Basic interface to the compiler.
State:
class hierarchy link, method dictionary, description of
instances (representation and number)
Methods:
creating a method dictionary, compiling method
instance creation (new, basicNew, new:, basicNew:)
class hierarchy manipulation (superclass:, addSubclass:)
accessing (selectors, allSelectors, compiledMethodAt: )
accessing instances and variables (allInstances,
instVarNames)
accessing class hierarchy (superclass, subclasses)
testing (hasMethods, includesSelector, canUnderstand:,
S.Ducasse 22
Responsibilities of ClassDescription
ClassDescription
adds a number of facilities to basic Behavior:
named instance variables
category organization for methods
the notion of a name (abstract)
maintenance of Change sets and logging changes
most of the mechanisms needed for fileOut
ClassDescription is an abstract class: its facilities are
intended for inheritance by the two subclasses, Class and
Metaclass.
S.Ducasse 23
Responsibilities of Class
Class
represents the common behavior of all classes
name, compilation, method storing, instance variables …
representation for classVariable names and shared pool
variables (addClassVarName:, addSharedPool:,
initialize)
Class inherits from Object because Class is an
Object
Class knows how to create instances, so all
metaclasses should inherit ultimately from Class
S.Ducasse 24
Metaclasses in 7 points
Every object is an instance of a class
Every class eventually inherits from Object
Every class is an instance of a metaclass
The metaclass hierarchy parallels the class hierarchy
Every metaclass inherits from Class and Behavior
Every metaclass is an instance of Metaclass
The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 25
6. Every metaclass is an instance of Metaclass
S.Ducasse 26
Metaclass Responsibilities
Metaclass
Represents common metaclass Behavior
instance creation (subclassOf:)
creating initialized instances of the metaclass’s sole
instance
initialization of class variables
metaclass instance protocol
(name:inEnvironment:subclassOf:....)
method compilation (different semantics can be
introduced)
class information (inheritance link, instance variable, ...)
S.Ducasse 27
Metaclasses in 7 points
Every object is an instance of a class
Every class eventually inherits from Object
Every class is an instance of a metaclass
The metaclass hierarchy parallels the class hierarchy
Every metaclass inherits from Class and Behavior
Every metaclass is an instance of Metaclass
The metaclass of Metaclass is an instance of
Metaclass
S.Ducasse 28
7.The metaclass of Metaclass is an instance of Metaclass
S.Ducasse 29
Navigating the metaclass
hierarchyMetaclassHierarchyTest>>testHierarchyMetaclassHierarchyTest>>testHierarchy
"The class hierarchy""The class hierarchy"
self assert: Snake superclass = Square.self assert: Snake superclass = Square.
self assert: Square superclass = Object.self assert: Square superclass = Object.
self assert: Object superclass superclass = nil. "skip ProtoObject"self assert: Object superclass superclass = nil. "skip ProtoObject"
"The parallel metaclass hierarchy""The parallel metaclass hierarchy"
self assert: Snake class name = 'Snake class'.self assert: Snake class name = 'Snake class'.
self assert: Snake class superclass = Square class.self assert: Snake class superclass = Square class.
self assert: Square class superclass = Object class.self assert: Square class superclass = Object class.
self assert: Object class superclass superclass = Class.self assert: Object class superclass superclass = Class.
self assert: Class superclass = ClassDescription.self assert: Class superclass = ClassDescription.
self assert: ClassDescription superclass = Behavior.self assert: ClassDescription superclass = Behavior.
self assert: Behavior superclass = Object.self assert: Behavior superclass = Object.
"The Metaclass hierarchy""The Metaclass hierarchy"
self assert: Snake class class = Metaclass.self assert: Snake class class = Metaclass.
self assert: Square class class = Metaclass.self assert: Square class class = Metaclass.
self assert: Object class class = Metaclass.self assert: Object class class = Metaclass.
self assert: Class class class = Metaclass.self assert: Class class class = Metaclass.
self assert: ClassDescription class class = Metaclass.self assert: ClassDescription class class = Metaclass.
self assert: Behavior class class = Metaclass.self assert: Behavior class class = Metaclass.
self assert: Metaclass superclass = ClassDescription.self assert: Metaclass superclass = ClassDescription.
"The fixpoint""The fixpoint"
self assert: Metaclass class class = Metaclass.self assert: Metaclass class class = Metaclass.
S.Ducasse 30
Roadmap
> Metaclasses in 7 points
> Indexed Classes
> Class InstanceVariables
> ClassVariables
> Pool Dictionaries
S.Ducasse 31
Two ways to represent objects
Named or indexed instance variables
Named: name of GamePlayer
Indexed: #(Jack Jill) at: 1
Or looking at them in another way:
Objects with pointers to other objects
Objects with arrays of bytes (word, long)
Difference for efficiency reasons:
arrays of bytes (like C strings) are faster than storing an
array of pointers, each pointing to a single byte.
S.Ducasse 32
Different methods to create classes
Indexed
Named Instance
Variables
Definition Method
No Yes #subclass: …
Yes Yes #variableSubclass: …
Yes No #variableByteSubclass: …
> See the subclass creation protocol of Class
> Constraints
— Pointer classes defined using #subclass: support any kind of subclasses
— Byte classes defined using #variableSubclass: can only have:
variableSubclass: or variableByteSubclass: subclasses
S.Ducasse 33
Testing methods
> See testing protocols of Behavior:
— #isPointers, #isBits, #isBytes, #isFixed, #isVariable
— #kindOfSubclass
Object allSubclasses select: [:class | class isBytes]
a Set(ByteArray MwSynchronizationWrapper
MwBlockMethodWrapper ExternalAddress MCMockClassH
LargeNegativeInteger LargePositiveInteger ByteSymbol
MwCountMethodWrapper MwTimeMethodWrapper
MwMethodWrapper MwBlockHandlerMethodWrapper
ByteString MwCalledMethodWrapper UUID CompiledMethod)
S.Ducasse 34
Defining Indexed Classes
Example — instantiating an Array:
ArrayedCollection variableSubclass: #Array
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Collections-Arrayed'
Array new: 4 #(nil nil nil nil)
#(1 2 3 4) class isVariable true
S.Ducasse 35
Defining an Indexed Class
Object variableSubclass: #IndexedObject
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: ''
(IndexedObject new: 2)
at: 1 put: 'Jack';
at: 2 put: 'Jill';
at: 1 'Jack'
S.Ducasse 36
Indexed Classes / Instance
Variables
An indexed variable is implicitly added to the list of
instance variables
Only one indexed instance variable per class
Access with at: and at:put:
NB: answers the value, not the receiver
Subclasses should also be indexed
S.Ducasse 37
Roadmap
> Metaclasses in 7 points
> Indexed Classes
> Class Instance Variables
> ClassVariables
> Pool Dictionaries
S.Ducasse 38
Class InstanceVariables
Class are objects too
Instances of their metaclass
Methods looked up in the method dictionary of their
metaclass
Can also define instance variables
When a metaclass defines a new instance variable, then
its instance (a Class) gets a new variable
I.e., in addition to subclass, superclasses,
methodDict…
Use class instance variables to represent the private state
of the class
E.g., number of instances, superclass etc.
Not to represent information shared by all instances!
S.Ducasse 39
Example: the Singleton
Pattern
A class having only one instance
We keep the unique instance created in an instance variable
WebServer classWebServer class
instanceVariableNames:instanceVariableNames: 'uniqueInstance’'uniqueInstance’
WebServer class>>WebServer class>>newnew
self error:self error: 'Use uniqueInstance to get the unique'Use uniqueInstance to get the unique
instance'instance'
WebServer class>>WebServer class>>uniqueInstanceuniqueInstance
uniqueInstance isNiluniqueInstance isNil
ifTrue: [uniqueInstance := self basicNew initialize].ifTrue: [uniqueInstance := self basicNew initialize].
^ uniqueInstance^ uniqueInstance
WebServer classWebServer class
instanceVariableNames:instanceVariableNames: 'uniqueInstance’'uniqueInstance’
WebServer class>>WebServer class>>newnew
self error:self error: 'Use uniqueInstance to get the unique'Use uniqueInstance to get the unique
instance'instance'
WebServer class>>WebServer class>>uniqueInstanceuniqueInstance
uniqueInstance isNiluniqueInstance isNil
ifTrue: [uniqueInstance := self basicNew initialize].ifTrue: [uniqueInstance := self basicNew initialize].
^ uniqueInstance^ uniqueInstance
S.Ducasse 40
Roadmap
> Metaclasses in 7 points
> Indexed Classes
> Class InstanceVariables
> Class Variables
> Pool Dictionaries
S.Ducasse 41
ClassVariable = SharedVariable
To share information amongst all instances of a class, use
a “class variable”
Shared and directly accessible by all the instances of the
class and subclasses
Accessible to both instance and class methods
Begins with an uppercase letter
S.Ducasse 42
Initializing class variables
Class variables should be initialized by an initialize
method on the class side
Magnitude subclass: #Date
instanceVariableNames: 'julianDayNumber '
classVariableNames: 'DaysInMonth FirstDayOfMonth
MonthNames SecondsInDay WeekDayNames '
poolDictionaries: ''
category: 'Kernel-Magnitudes'
Date class>>initialize
...
WeekDayNames := #(Sunday Monday ...).
MonthNames := #(January February ... ).
DaysInMonth := #(31 28 31 30 31 30 31 31 30 31 30 31).
S.Ducasse 43
ClassVariables vs. Instance
Variables
S.Ducasse 44
Roadmap
> Metaclasses in 7 points
> Indexed Classes
> Class InstanceVariables
> ClassVariables
> Pool Dictionaries
S.Ducasse 45
Pool Dictionaries
A Pool Dictionary is a shared variable
Begins with a uppercase letter.
Shared by a group of classes not linked by inheritance.
Each class possesses its own pool dictionary (containing
pool variables).
They are not inherited.
Don’t use them!
S.Ducasse 46
Examples of Pool Dictionaries
ArrayedCollection subclass: #Text
instanceVariableNames: 'string runs'
classVariableNames: ''
poolDictionaries: 'TextConstants'
category: 'Collections-Text'
Elements stored into TextConstants
like Ctrl, CR, ESC, Space can be
directly accessed from all the classes
like ParagraphEditor....
Hint: You can inspect any Pool
Dictionary
S.Ducasse 47
Smalltalk System Dictionary
Pool Dictionaries are stored in the Smalltalk system
dictionary
Smalltalk inspect
(Smalltalk at: #TextConstants) at: #ESC $
S.Ducasse 48
Accessing globals
Use message-sending instead of directly accessing pool
variables
stream nextPut: Lfstream nextPut: Lf "A pool variable visible to the class""A pool variable visible to the class"
stream nextPut: Character lfstream nextPut: Character lfvs.vs.vs.vs.
S.Ducasse 49
What you should know!
What does is-a mean?
What is the difference between sending a message to an
object and to its class?
What are the responsibilities of a metaclass?
What is the superclass of Object class?
Where is new defined?
What is the difference between class variables and class
instance variables?
S.Ducasse 50
Can you answer these questions?
Why are there no explicit metaclasses?
When should you override new?
Why don’t metaclasses inherit from Class?
Are there any classes that don’t inherit from Object?
Is Metaclass a Class? Why or why not?
Where are the methods class and superclass defined?
When should you define an indexed class?
Are Java static variables just like class variables or class
instance variables?
Where is the SystemDictionary Smalltalk defined?
S.Ducasse 51
License: CC-Attribution-ShareAlike 2.0
http://creativecommons.org/licenses/by-sa/2.0/

Mais conteúdo relacionado

Destaque (20)

Stoop 415-design points
Stoop 415-design pointsStoop 415-design points
Stoop 415-design points
 
8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model8 - OOP - Smalltalk Model
8 - OOP - Smalltalk Model
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop 423-some designpatterns
Stoop 423-some designpatternsStoop 423-some designpatterns
Stoop 423-some designpatterns
 
Stoop 434-composite
Stoop 434-compositeStoop 434-composite
Stoop 434-composite
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)9 - OOP - Smalltalk Classes (b)
9 - OOP - Smalltalk Classes (b)
 
Stoop 431-visitor
Stoop 431-visitorStoop 431-visitor
Stoop 431-visitor
 
Stoop 300-block optimizationinvw
Stoop 300-block optimizationinvwStoop 300-block optimizationinvw
Stoop 300-block optimizationinvw
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop 400-metaclass only
Stoop 400-metaclass onlyStoop 400-metaclass only
Stoop 400-metaclass only
 

Semelhante a Understanding Metaclasses (20)

Stoop 304-metaclasses
Stoop 304-metaclassesStoop 304-metaclasses
Stoop 304-metaclasses
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Java session2
Java session2Java session2
Java session2
 
Ruby's metaclass
Ruby's metaclassRuby's metaclass
Ruby's metaclass
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over Classes
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Aman kingrubyoo pnew
Aman kingrubyoo pnew Aman kingrubyoo pnew
Aman kingrubyoo pnew
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Chapter 9 java
Chapter 9 javaChapter 9 java
Chapter 9 java
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
Stoop 421-design heuristics
Stoop 421-design heuristicsStoop 421-design heuristics
Stoop 421-design heuristics
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
ACM init() Day 6
ACM init() Day 6ACM init() Day 6
ACM init() Day 6
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Oops
OopsOops
Oops
 
Week3 dq1
Week3 dq1Week3 dq1
Week3 dq1
 

Mais de The World of Smalltalk (20)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
10 reflection
10 reflection10 reflection
10 reflection
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
07 bestpractice
07 bestpractice07 bestpractice
07 bestpractice
 
06 debugging
06 debugging06 debugging
06 debugging
 
05 seaside
05 seaside05 seaside
05 seaside
 
04 idioms
04 idioms04 idioms
04 idioms
 
02 basics
02 basics02 basics
02 basics
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 

Understanding Metaclasses

  • 2. S.Ducasse 2 Roadmap • Metaclasses in 7 points • Indexed Classes • Class InstanceVariables • ClassVariables • Pool Dictionaries
  • 3. S.Ducasse 3 Metaclasses in 7 points 1. Every object is an instance of a class 2. Every class eventually inherits from Object 3. Every class is an instance of a metaclass 4. The metaclass hierarchy parallels the class hierarchy 5. Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass Adapted from Goldberg & Robson, Smalltalk-80 — The Language
  • 4. S.Ducasse 4 Metaclasses in 7 points 1.Every object is an instance of a class 2. Every class eventually inherits from Object 3. Every class is an instance of a metaclass 4. The metaclass hierarchy parallels the class hierarchy 5. Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass
  • 5. S.Ducasse 5 1. Every object is an instance of a class
  • 6. S.Ducasse 6 Metaclasses in 7 points 1. Every object is an instance of a class 2.Every class eventually inherits from Object 3. Every class is an instance of a metaclass 4. The metaclass hierarchy parallels the class hierarchy 5. Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass
  • 7. S.Ducasse 7 2. Every class inherits from Object Every object is-an Object = The class of every object ultimately inherits from Object
  • 8. S.Ducasse 8 The Meaning of is-a • When an object receives a message, the method is looked up in the method dictionary of its class, and, if necessary, its superclasses, up to Object
  • 9. S.Ducasse 9 Responsibilities of Object • Object • represents the common object behavior • error-handling, halting … • all classes should inherit ultimately from Object
  • 10. S.Ducasse 10 Metaclasses in 7 points 1. Every object is an instance of a class 2. Every class eventually inherits from Object 3.Every class is an instance of a metaclass 4. The metaclass hierarchy parallels the class hierarchy 5. Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass
  • 11. S.Ducasse 11 3. Every class is an instance of a metaclass • Classes are objects too! • Every class X is the unique instance of its metaclass, called X class
  • 12. S.Ducasse 12 Metaclasses are implicit • There are no explicit metaclasses • Metaclasses are created implicitly when classes are created • No sharing of metaclasses (unique metaclass per class)
  • 13. S.Ducasse 13 Metaclasses by Example Square allSubclassesSquare allSubclasses Snake allSubclassesSnake allSubclasses Snake allInstancesSnake allInstances Snake instVarNamesSnake instVarNames Snake back: 5Snake back: 5 Snake selectorsSnake selectors Snake canUnderstand: #newSnake canUnderstand: #new Snake canUnderstand: #setBack:Snake canUnderstand: #setBack:
  • 14. S.Ducasse 14 Metaclasses in 7 points 1. Every object is an instance of a class 2. Every class eventually inherits from Object 3. Every class is an instance of a metaclass 4.The metaclass hierarchy parallels the class hierarchy 5. Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass
  • 15. S.Ducasse 15 4.The metaclass hierarchy parallels the class hierarchy
  • 16. S.Ducasse 16 Uniformity between Classes and Objects • Classes are objects too, so … • Everything that holds for objects holds for classes as well • Same method lookup strategy • Look up in the method dictionary of the metaclass
  • 18. S.Ducasse 18 Metaclasses in 7 points 1. Every object is an instance of a class 2. Every class eventually inherits from Object 3. Every class is an instance of a metaclass 4. The metaclass hierarchy parallels the class hierarchy 5.Every metaclass inherits from Class and Behavior 6. Every metaclass is an instance of Metaclass 7. The metaclass of Metaclass is an instance of Metaclass
  • 19. S.Ducasse 19 5. Every metaclass inherits from Class and Behavior • Every class is-a Class = The metaclass of every class inherits from Class
  • 20. S.Ducasse 20 Where is new defined?
  • 21. S.Ducasse 21 Responsibilities of Behavior Behavior Minimum state necessary for objects that have instances. Basic interface to the compiler. State: class hierarchy link, method dictionary, description of instances (representation and number) Methods: creating a method dictionary, compiling method instance creation (new, basicNew, new:, basicNew:) class hierarchy manipulation (superclass:, addSubclass:) accessing (selectors, allSelectors, compiledMethodAt: ) accessing instances and variables (allInstances, instVarNames) accessing class hierarchy (superclass, subclasses) testing (hasMethods, includesSelector, canUnderstand:,
  • 22. S.Ducasse 22 Responsibilities of ClassDescription ClassDescription adds a number of facilities to basic Behavior: named instance variables category organization for methods the notion of a name (abstract) maintenance of Change sets and logging changes most of the mechanisms needed for fileOut ClassDescription is an abstract class: its facilities are intended for inheritance by the two subclasses, Class and Metaclass.
  • 23. S.Ducasse 23 Responsibilities of Class Class represents the common behavior of all classes name, compilation, method storing, instance variables … representation for classVariable names and shared pool variables (addClassVarName:, addSharedPool:, initialize) Class inherits from Object because Class is an Object Class knows how to create instances, so all metaclasses should inherit ultimately from Class
  • 24. S.Ducasse 24 Metaclasses in 7 points Every object is an instance of a class Every class eventually inherits from Object Every class is an instance of a metaclass The metaclass hierarchy parallels the class hierarchy Every metaclass inherits from Class and Behavior Every metaclass is an instance of Metaclass The metaclass of Metaclass is an instance of Metaclass
  • 25. S.Ducasse 25 6. Every metaclass is an instance of Metaclass
  • 26. S.Ducasse 26 Metaclass Responsibilities Metaclass Represents common metaclass Behavior instance creation (subclassOf:) creating initialized instances of the metaclass’s sole instance initialization of class variables metaclass instance protocol (name:inEnvironment:subclassOf:....) method compilation (different semantics can be introduced) class information (inheritance link, instance variable, ...)
  • 27. S.Ducasse 27 Metaclasses in 7 points Every object is an instance of a class Every class eventually inherits from Object Every class is an instance of a metaclass The metaclass hierarchy parallels the class hierarchy Every metaclass inherits from Class and Behavior Every metaclass is an instance of Metaclass The metaclass of Metaclass is an instance of Metaclass
  • 28. S.Ducasse 28 7.The metaclass of Metaclass is an instance of Metaclass
  • 29. S.Ducasse 29 Navigating the metaclass hierarchyMetaclassHierarchyTest>>testHierarchyMetaclassHierarchyTest>>testHierarchy "The class hierarchy""The class hierarchy" self assert: Snake superclass = Square.self assert: Snake superclass = Square. self assert: Square superclass = Object.self assert: Square superclass = Object. self assert: Object superclass superclass = nil. "skip ProtoObject"self assert: Object superclass superclass = nil. "skip ProtoObject" "The parallel metaclass hierarchy""The parallel metaclass hierarchy" self assert: Snake class name = 'Snake class'.self assert: Snake class name = 'Snake class'. self assert: Snake class superclass = Square class.self assert: Snake class superclass = Square class. self assert: Square class superclass = Object class.self assert: Square class superclass = Object class. self assert: Object class superclass superclass = Class.self assert: Object class superclass superclass = Class. self assert: Class superclass = ClassDescription.self assert: Class superclass = ClassDescription. self assert: ClassDescription superclass = Behavior.self assert: ClassDescription superclass = Behavior. self assert: Behavior superclass = Object.self assert: Behavior superclass = Object. "The Metaclass hierarchy""The Metaclass hierarchy" self assert: Snake class class = Metaclass.self assert: Snake class class = Metaclass. self assert: Square class class = Metaclass.self assert: Square class class = Metaclass. self assert: Object class class = Metaclass.self assert: Object class class = Metaclass. self assert: Class class class = Metaclass.self assert: Class class class = Metaclass. self assert: ClassDescription class class = Metaclass.self assert: ClassDescription class class = Metaclass. self assert: Behavior class class = Metaclass.self assert: Behavior class class = Metaclass. self assert: Metaclass superclass = ClassDescription.self assert: Metaclass superclass = ClassDescription. "The fixpoint""The fixpoint" self assert: Metaclass class class = Metaclass.self assert: Metaclass class class = Metaclass.
  • 30. S.Ducasse 30 Roadmap > Metaclasses in 7 points > Indexed Classes > Class InstanceVariables > ClassVariables > Pool Dictionaries
  • 31. S.Ducasse 31 Two ways to represent objects Named or indexed instance variables Named: name of GamePlayer Indexed: #(Jack Jill) at: 1 Or looking at them in another way: Objects with pointers to other objects Objects with arrays of bytes (word, long) Difference for efficiency reasons: arrays of bytes (like C strings) are faster than storing an array of pointers, each pointing to a single byte.
  • 32. S.Ducasse 32 Different methods to create classes Indexed Named Instance Variables Definition Method No Yes #subclass: … Yes Yes #variableSubclass: … Yes No #variableByteSubclass: … > See the subclass creation protocol of Class > Constraints — Pointer classes defined using #subclass: support any kind of subclasses — Byte classes defined using #variableSubclass: can only have: variableSubclass: or variableByteSubclass: subclasses
  • 33. S.Ducasse 33 Testing methods > See testing protocols of Behavior: — #isPointers, #isBits, #isBytes, #isFixed, #isVariable — #kindOfSubclass Object allSubclasses select: [:class | class isBytes] a Set(ByteArray MwSynchronizationWrapper MwBlockMethodWrapper ExternalAddress MCMockClassH LargeNegativeInteger LargePositiveInteger ByteSymbol MwCountMethodWrapper MwTimeMethodWrapper MwMethodWrapper MwBlockHandlerMethodWrapper ByteString MwCalledMethodWrapper UUID CompiledMethod)
  • 34. S.Ducasse 34 Defining Indexed Classes Example — instantiating an Array: ArrayedCollection variableSubclass: #Array instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Collections-Arrayed' Array new: 4 #(nil nil nil nil) #(1 2 3 4) class isVariable true
  • 35. S.Ducasse 35 Defining an Indexed Class Object variableSubclass: #IndexedObject instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: '' (IndexedObject new: 2) at: 1 put: 'Jack'; at: 2 put: 'Jill'; at: 1 'Jack'
  • 36. S.Ducasse 36 Indexed Classes / Instance Variables An indexed variable is implicitly added to the list of instance variables Only one indexed instance variable per class Access with at: and at:put: NB: answers the value, not the receiver Subclasses should also be indexed
  • 37. S.Ducasse 37 Roadmap > Metaclasses in 7 points > Indexed Classes > Class Instance Variables > ClassVariables > Pool Dictionaries
  • 38. S.Ducasse 38 Class InstanceVariables Class are objects too Instances of their metaclass Methods looked up in the method dictionary of their metaclass Can also define instance variables When a metaclass defines a new instance variable, then its instance (a Class) gets a new variable I.e., in addition to subclass, superclasses, methodDict… Use class instance variables to represent the private state of the class E.g., number of instances, superclass etc. Not to represent information shared by all instances!
  • 39. S.Ducasse 39 Example: the Singleton Pattern A class having only one instance We keep the unique instance created in an instance variable WebServer classWebServer class instanceVariableNames:instanceVariableNames: 'uniqueInstance’'uniqueInstance’ WebServer class>>WebServer class>>newnew self error:self error: 'Use uniqueInstance to get the unique'Use uniqueInstance to get the unique instance'instance' WebServer class>>WebServer class>>uniqueInstanceuniqueInstance uniqueInstance isNiluniqueInstance isNil ifTrue: [uniqueInstance := self basicNew initialize].ifTrue: [uniqueInstance := self basicNew initialize]. ^ uniqueInstance^ uniqueInstance WebServer classWebServer class instanceVariableNames:instanceVariableNames: 'uniqueInstance’'uniqueInstance’ WebServer class>>WebServer class>>newnew self error:self error: 'Use uniqueInstance to get the unique'Use uniqueInstance to get the unique instance'instance' WebServer class>>WebServer class>>uniqueInstanceuniqueInstance uniqueInstance isNiluniqueInstance isNil ifTrue: [uniqueInstance := self basicNew initialize].ifTrue: [uniqueInstance := self basicNew initialize]. ^ uniqueInstance^ uniqueInstance
  • 40. S.Ducasse 40 Roadmap > Metaclasses in 7 points > Indexed Classes > Class InstanceVariables > Class Variables > Pool Dictionaries
  • 41. S.Ducasse 41 ClassVariable = SharedVariable To share information amongst all instances of a class, use a “class variable” Shared and directly accessible by all the instances of the class and subclasses Accessible to both instance and class methods Begins with an uppercase letter
  • 42. S.Ducasse 42 Initializing class variables Class variables should be initialized by an initialize method on the class side Magnitude subclass: #Date instanceVariableNames: 'julianDayNumber ' classVariableNames: 'DaysInMonth FirstDayOfMonth MonthNames SecondsInDay WeekDayNames ' poolDictionaries: '' category: 'Kernel-Magnitudes' Date class>>initialize ... WeekDayNames := #(Sunday Monday ...). MonthNames := #(January February ... ). DaysInMonth := #(31 28 31 30 31 30 31 31 30 31 30 31).
  • 43. S.Ducasse 43 ClassVariables vs. Instance Variables
  • 44. S.Ducasse 44 Roadmap > Metaclasses in 7 points > Indexed Classes > Class InstanceVariables > ClassVariables > Pool Dictionaries
  • 45. S.Ducasse 45 Pool Dictionaries A Pool Dictionary is a shared variable Begins with a uppercase letter. Shared by a group of classes not linked by inheritance. Each class possesses its own pool dictionary (containing pool variables). They are not inherited. Don’t use them!
  • 46. S.Ducasse 46 Examples of Pool Dictionaries ArrayedCollection subclass: #Text instanceVariableNames: 'string runs' classVariableNames: '' poolDictionaries: 'TextConstants' category: 'Collections-Text' Elements stored into TextConstants like Ctrl, CR, ESC, Space can be directly accessed from all the classes like ParagraphEditor.... Hint: You can inspect any Pool Dictionary
  • 47. S.Ducasse 47 Smalltalk System Dictionary Pool Dictionaries are stored in the Smalltalk system dictionary Smalltalk inspect (Smalltalk at: #TextConstants) at: #ESC $
  • 48. S.Ducasse 48 Accessing globals Use message-sending instead of directly accessing pool variables stream nextPut: Lfstream nextPut: Lf "A pool variable visible to the class""A pool variable visible to the class" stream nextPut: Character lfstream nextPut: Character lfvs.vs.vs.vs.
  • 49. S.Ducasse 49 What you should know! What does is-a mean? What is the difference between sending a message to an object and to its class? What are the responsibilities of a metaclass? What is the superclass of Object class? Where is new defined? What is the difference between class variables and class instance variables?
  • 50. S.Ducasse 50 Can you answer these questions? Why are there no explicit metaclasses? When should you override new? Why don’t metaclasses inherit from Class? Are there any classes that don’t inherit from Object? Is Metaclass a Class? Why or why not? Where are the methods class and superclass defined? When should you define an indexed class? Are Java static variables just like class variables or class instance variables? Where is the SystemDictionary Smalltalk defined?
  • 51. S.Ducasse 51 License: CC-Attribution-ShareAlike 2.0 http://creativecommons.org/licenses/by-sa/2.0/