December 22, 2024
Instance and Class Methods
Instance methods are available for use by any instance
of a class and any instance of any subclass. A Frog
instance gets a position message and that triggers
the position method that is encapsulated in
that Frog instance.
A class method is executed when a class object (all classes are objects)
is sent a class message. Class methods are often used for creating initialized
instances of a class.
For example later in the course you will be using a class called Lottery.
It has a class method called new
new
"Answer with an initialised instance of the receiver
class; use new
from superclass, then initialise instance."
^super new initialize
This class method creates a new instance and sends it an instance message
intialize.
By evaluating
aLottery := Lottery new
aLottery references an initialised instance of Lottery
Class methods are also used for holding data. For example Float
has a class variable called Pi (all class variables
start uppercase) and a class method
pi
"Answer the constant, Pi."
^Pi
Float (a class object) stores a constant referenced by Pi, the value of Pi, and this value can be returned by sending the object Float the class message pi
Float pi
Answers 3.14159
Another use for class variables is to keep a count of all instances that have been created. The class variable e.g. FrogCount, will simply reference an integer object and each time this particular class object (Frog) receives a new message, FrogCount is incremented.
A class is an object that can create instances. If that class has a class variable, any instance of that class can make direct reference to that class variable within an instance method and so can any instance of a subclass. Furthermore, that class variable can be accessed directly by any class method of that class and any class method of its subclasses. Consequently, you could write an instance method for a class and inside the method body make use of the class variable. Smalltalk would insert the value of that class variable when the instance method was executed.
Don't concern yourself with class instance variables because they are not used in M206.
⇑ Up to top of page