Working with Classes and Objects in Smalltalk: A Hands-On Approach

July 17, 2024

Welcome to another exciting lesson in our Smalltalk series! In this post, we will delve into the world of classes and objects in Smalltalk, providing you with a hands-on approach to understanding and working with these fundamental concepts.

Defining Classes in Smalltalk

In Smalltalk, classes are the blueprints for creating objects. To define a class, you use the class keyword followed by the class name and a pair of curly braces to enclose the class definition. Here’s an example of defining a simple class named Person:

Object subclass: #Person
    instanceVariableNames: 'name age'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'MyApp'

In this example, we define a class Person with instance variables name and age.

Creating Objects in Smalltalk

Once you have defined a class, you can create objects of that class using the new message. Here’s how you can create an instance of the Person class:

person := Person new.
person name: 'Alice'.
person age: 30.

In this code snippet, we create a new instance of the Person class and set the values of the name and age instance variables.

Establishing Relationships Between Objects

In Smalltalk, objects communicate with each other by sending messages. To establish relationships between objects, you can send messages to objects to interact with them. Here’s an example of how objects can interact in Smalltalk:

person1 := Person new.
person1 name: 'Alice'.
person1 age: 30.

person2 := Person new.
person2 name: 'Bob'.
person2 age: 25.

person1 sayHelloTo: person2.

Person>>sayHelloTo: aPerson
    Transcript show: 'Hello ', aPerson name; show: '!'; cr.

In this example, we create two instances of the Person class and have them interact by sending a message sayHelloTo: to greet each other.

By understanding how to define classes, create objects, and establish relationships between objects in Smalltalk, you are well on your way to mastering object-oriented programming in this powerful language. Stay tuned for more exciting lessons in our Smalltalk series!