March 19, 2024

Class Methods

 

A class acts as a template for creating objects. However this begs the question, where do classes come from?

It is necessary to realise that a class is an object. It is manufactured by another object, an instance of Metaclass.

A class, being an object, also has a protocol, which means that objects such as Frog and Dialog can respond to class messages. Here are some examples:

aFrog := Frog new
new is a class message
Dialog warn: 'You entered an incorrect password'
warn: is a class message

Consequently, class methods are required in order to implement class messages. Here is the new class method for Artwork.

new
   "Answer with an initialised instance of the receiver
   class; use new from superclass, then initialise
   instance."
   ^super new initialize

Sending the message new to Artwork creates an initialized instance of that class. The pseudo-variable super will, like self, reference the receiver of the message that triggered the method that contains super. However, there is a difference because super tells the receiver to ignore the method in its own class and look up the class hierarchy, to its superclass, in order to find a method of the same name. This method 'look up' continues until that method is found and executed. If the method is not found, the system will throw an error.

You may find it strange that the lookup for new does not end in the superclass of Artwork, Object. Similarly, neither does Frog find new in Object. It is found in Behavior, but don't concern yourself with the mechanism that Smalltalk uses to achieve this.

When new is found it is executed and an instance of the receiver, Artwork, is created. Next, the Artwork object receives the initialize message. This message has already been implemented, so new is reusing code written for the initialize method. This method instructs the object to set its instance variable title to the string 'untitled'. Lastly, new returns this initialised object as its message answer.

It always helps to think about what is happening in terms of objects and messages.

  1. Which object is the receiver?
  2. What message is being sent?
  3. Does the receiver understand the message?
  4. If it does, what is the message answer?
  5. What class of object is the message answer?
  6. Is that message answer used in some way? e.g. passed as the argument to some other message?
  7. Is an object sending a message to itself?

We can use variable reference and object-interaction diagrams to illustrate objects, variables, messages and message answers.

Next page » Variable reference diagrams

Previous page « self

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page