I'm new to GNU Smalltalk. I'd like to port a script I've written in Ruby, Scala, CoffeeScript, and several others. It's the one I use to try to learn the classic OOP concepts of abstract classes, abstract methods, overriding, dispatch, etc. It goes like this:
- Define an abstract class
Animal
with a constructor to set the animal's name, aspeak
method to return a stringN says S
whereN
is the name andS
is the sound the animal makes. - Define three concrete subclasses
Horse
,Cow
, andSheep
, each with their own sound-returning string method. - Create a horse and sheep and a cow, and make them speak. For the horse and cow, create a variable. For the sheep, call the speak method on an "anonymous" object.
My GNU Smalltalk solution is:
Object subclass: Animal [
| name |
Animal class >> new: n [^super new init: n]
init: n [name := n]
speak [^name, ' says ', self sound]
]
Animal subclass: Horse [
sound [^'neigh']
]
Animal subclass: Sheep [
sound [^'baaaa']
]
Animal subclass: Cow [
sound [^'moooo']
]
h := Horse new: 'CJ'.
h speak displayNl.
c := Cow new: 'Bessie'.
c speak displayNl.
(Sheep new: 'Little Lamb') speak displayNl.
I get the expected output but I am unhappy with the solution. I'd appreciate input on:
- The whole
new
andinit
thing. Is there a way to make it cleaner? - I noticed I did not have to override
new
orinit
in my subclasses; did the subclasses really inheritnew
? It is a classmethod and I don't know if it is inherited or not. - Are we supposed to give an implementation of
new
? I had heard this was not a good idea. I know from Ruby that you just defineinitialize
and use the built-innew
to automatically invoke theinitialize
instance method. - Is this GNU Smalltalk syntax I got from the GNU tutorial proper or is it an extension of some sort? Should this be written in a proper, "purer" Smalltalk style? I've seen some where there is an
instanceVariables
message. - I know Smalltalk has something called
subclassResponsibility
. Is it wise to declare thesound
method in theAnimal
class (as an abstract method)?