Navigation:  Tutorials > Beginners Guide to Smalltalk > Programming in Smalltalk > Representing an object as text >

#printString and #printOn:

Previous pageReturn to chapter overviewNext page

These messages are used in a similar way to the #displayString and #displayOn: methods except that they are intended to create a textual representation of an object as a developer (a rather than an end-user) would wish to see it. The default implementation of these methods in Object will merely tell the developer what the class of the object is (e.g. an Animal). Now let us override #printOn: to also display the animal's name along with its class.

printOn: aStream

       "Answer the name of the receiver as a developer would wish to see it."

       super printOn: aStream.

       aStream nextPut: $(.

       self displayOn: aStream.

       aStream nextPut: $).


To test this in the workspace, display the result of evaluating the following.

"Print this"

tiger printString.


If everything has gone according to plan this should print as "an Animal(a Tiger)". Whenever you add a new class to your image you should probably consider overriding one or more of the #displayOn: and #printOn: methods. You might want to do this even if you don't need to represent your object as text in your initial design; it's very likely that this could become a requirement at sometime in the future.