Class and Method Definitions

Damien Cassou, St├ęphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

Class and Method Definitions in Pharo

Class Definition in Pharo

Class Definition is a Message

Object subclass: #Point
  instanceVariableNames: 'x y'
  classVariableNames: ''
  package: 'Graphics'

We send the message subclass:inst.... to the superclass to create the class

Method Definition in Pharo

Method Definition in Pharo

factorial
  "Answer the factorial of the receiver."
  self = 0 ifTrue: [ ^ 1 ].
  self > 0 ifTrue: [ ^ self * (self - 1) factorial ].
  self error: 'Not valid for negative integers'

In which class is factorial defined?

Presentation Convention

In this lecture, a method will be displayed as

Integer >> factorial
  "Answer the factorial of the receiver."
  self = 0 ifTrue: [ ^ 1 ].
  self > 0 ifTrue: [ ^ self * (self - 1) factorial ].
  self error: 'Not valid for negative integers'

Presentation Convention

In Pharo, the method belongs to the selected class

Remember Messages

Integer >> factorial
  "Answer the factorial of the receiver."

  self = 0 ifTrue: [ ^ 1 ].
  self > 0 ifTrue: [ ^ self * (self - 1) factorial ].
  self error: 'Not valid for negative integers'

A Method Returns self by Default

Game >> initializePlayers
  self players
    at: 'tileAction'
    put: ( MITileAction director: self )

is equivalent to

Game >> initializePlayers
  self players
    at: 'tileAction'
    put: ( MITileAction director: self ).
  ^ self       "<-- optional"

Class Methods

  • press the button class to define a class method
  • in lectures, we add class
Point class >> x: xInteger y: yInteger 
  "Answer an instance of me with coordinates xInteger and yInteger."

  ^ self basicNew setX: xInteger setY: yInteger

What You Should Know

/