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
Animalwith a constructor to set the animal's name, a
speakmethod to return a string
N says Swhere
Nis the name and
Sis the sound the animal makes.
- Define three concrete subclasses
Sheep, 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
initthing. Is there a way to make it cleaner?
- I noticed I did not have to override
initin my subclasses; did the subclasses really inherit
new? 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 define
initializeand use the built-in
newto automatically invoke the
- 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
- I know Smalltalk has something called
subclassResponsibility. Is it wise to declare the
soundmethod in the
Animalclass (as an abstract method)?