The Can Class

The Can class serves as a very simple example of creating a class, the description for an object. We create a Can class that has two attributes: body and contents. We provide accessors, "getters" and "setters," to provide the public interface to the class's protected contents. We have also provided a method, "demoCans," that tests and demonstrates the class.

Here is the (simplified) source code. This is mostly a Smalltalk tutorial, so you will need to learn somewhere else how to enter code into the Squeak image. Don't worry, the tools are great and there are quite a few other tutorials out there to help you get started. The first place to go is http://www.squeak.org/.

Object subclass: #Can
  instanceVariableNames: 'body contents '
  classVariableNames: ''
  poolDictionaries: ''
  category: 'LunchDemo'

comment:
  This class models a simple can for the LunchDemo tutorial.  an is a 
  very simple class that encapsulates two attributes: body and 
  contents.  It includes simple accessors, 'getters' and 'setters,' 
  that form the object's public interface.  It also includes a 
  demonstration method, 'demoCans.'

  To test the Can class, select the next line and inspect it:
    Can new demoCans.

body
  "Returns the current value of the body attribute."  
  ^ body.

body: typeofmetal
  "Sets the value of the body attribute."
  body_typeofmetal.
  self contentsChanged

contents
  "Returns the current value of the contents attribute."
  ^ contents.

contents: newContents
  "Sets the value of the contents attribute."
  contents_newContents.
  self contentsChanged

demoCans
  "Demonstrates and tests the class."
  | mycan othercan |
  mycan _ Can new.
  mycan body: 'tin'.
  mycan contents: 'spam'.
  othercan _ Can new.
  othercan body: 'aluminum'.
  othercan contents: 'cream soda'.
  (Transcript show: 'mycan:') cr.
  (Transcript show: '   Body = ', (mycan body)) cr.
  (Transcript show: '   Contents = ', (mycan contents)) cr.
  (Transcript show: 'othercan:') cr.
  (Transcript show: '   Body = ', (othercan body)) cr.
  (Transcript show: '   Contents', (othercan contents)) cr.