#displayString and #displayOn:
It is generally assumed that these messages can be used to display any object as an end-user would expect to see them. The first, #displayString, will answer a String representation of the object. The second takes a Stream as its only parameter and outputs the textual representation of the object to this stream. Streams are a more advanced subject so we won't go into too much detail about them here. The thing to note, however, is that #displayString is usually implemented in terms of #displayOn:. This means that if we need to change the way an object is represented as end-user text we normally only need to implement a #displayOn: method. First of all, let us see how an Animal responds to #displayString by default. Try executing the following example in a workspace.
tiger := Animal name: 'Tiger'.
Now, displaying this just as a "an Animal" is surely a little lackluster. Let's override the default implementation of #displayOn: (found in Object and which provides the grunt work for #displayString) to at least report the name of the animal involved. Add the following method to Animal.
Important: Since this is to be an instance side method, make sure you click the Instance button in the browser first.
"Answer the name of the receiver prepended by 'a' or 'an' as appropriate"
| aOrAn |
aOrAn := name first isVowel ifTrue: ['an '] ifFalse: ['a '].
aStream nextPutAll: aOrAn; nextPutAll: self name.
Now try testing #displayString again and you should see a more user-friendly representation of the tiger:
Writing a method like this in a derived class, which has the same name as a method in a superclass, is known as overriding the original method. This is another important aspect that forms part of object-oriented programming.