What is the Smalltalk equivalent of Java's static fields and methods? IOW, what do the Smalltalkers do when they need class level data and/or methods?
We use class-side methods/instance variables. A class is an object, after all, so can have methods.
For instance, the Rectangle class has a method #origin:corner: so you may write
Rectangle origin: 0@0 corner: 100@100
to create a Rectangle. This is just the message #origin:corner: sent to the object called Rectangle (a class is an object!) with the two Points as parameters.
Class-side instance variables work much the same way. A class, being an object, may have instance variables. From the SUnit library:
TestCase class
instanceVariableNames: 'history'
and then TestCase class exposes this in the usual way, with a getter/setter (#history and #history:).
EDIT: The @ I used has caused a fair bit of discussion. It's what's called a binary message, which allows one to define selectors that look just what other languages would call infix operators. For instance, 3 + 4, or 0@0. In the case of @, the Number class defines a method called @ taking a parameter y, defined as ^Point x: self y: y - "return a Point whose x coordinate is my own value and whose y coordinate is the parameter".
Point is an ordered pair, but of course there's nothing stopping one from defining higher-dimensional versions. Point might define a method called @ that looked like this, for instance: ^Triple x: self x y: self y z: z - "return a point in R^3 whose x, y coordinates are my own, and whose z coordinate is the given parameter".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With