Jebathon
Jebathon

Reputation: 4561

Calling a Constructor Method in Smalltalk

I have a class that makes car objects. It has two instance variables: Make and Color. I am having an issue calling this method within the workspace (noted below)

Class Method -Constructor

make: aMake color: aColor
    "Creates a new car object, sets its instance variables by the arguments"
    |car|
    car := self new.
    car setMake: aMake setColor: aColor. "accessor method below"
    ^car

Accessor Method

setMake: make setColor: color
    "sets the instance variables"
    Make := make.
    Color := color.

Workspace (calling code)

|car|
car := Car make: 'toyota' color: 'red'

I get 'Message Not Understood' when calling this line. What is the issue here?

Upvotes: 2

Views: 1212

Answers (3)

philippeback
philippeback

Reputation: 801

The reference book for doing all of these things right is:

http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X

Click on the "Look Inside" picture and you'll be able to get to the table of contents and the constructor method receipe.

I obviously can't copy the thing here, so here is a small extract picture.

Constructor Method

Upvotes: 0

Sean DeNigris
Sean DeNigris

Reputation: 6390

Everything looks alright. The likely gotcha would be that your "constructor" (which would more likely be called an "instance creation message" in Smalltalk) needs to be implemented on the class side, and you may have done so on the instance side. Conversely, your set... must be on the instance side. Which message is not understood (error details always help)? It should say in the debugger and that would help clarify.

Upvotes: 7

Stephan Eggermont
Stephan Eggermont

Reputation: 15907

I notice two additional issues with your code:

  • in smalltalk we don't use 'set' for setters
  • the instance variables have a lowercase initial.

So the initializer would be

make: aMake color: aColor
   "sets the instance variables"
    make := aMake.
    color := aColor.

Upvotes: 0

Related Questions