Search code examples
oopconstructorsmalltalkvisual-age

How to make instances of a class in Smalltalk?


I'm new in Smalltalk (VisualAge environment) and I try to make a class that counts number of her instances. Unfortunately something dosen't work when I override the 'new' method. This is my class code:

Object subclass: #TestClassB
    instanceVariableNames: 'niceVariable '
    classVariableNames: 'InstanceCounter '
    poolDictionaries: ''!

!TestClassB class publicMethods !

initWithNiceParameter: parameter

    |testClassBInstance|

    testClassBInstance:= self new.
    ^(testClassBInstance niceVariable: parameter)!

new
    super new.
    InstanceCounter isNil
        ifTrue: [InstanceCounter := 0] 
        ifFalse: [InstanceCounter := InstanceCounter + 1].
    ^self
    ! !

!TestClassB publicMethods !

niceVariable: anObject
    "Save the value of niceVariable."
    niceVariable := anObject.
! !

I'd like to create new object with 'initWithNiceParameter' message:

TestClassB initWithNiceParameter: 'my super string'

But all I get is error:

TestClassB does not understand niceVariable:

It's because 'TestClassB' is also an object and seems it has no 'niceVariable' setter.

Do you have any idea how to create objects, when 'new' method is overrided?


Solution

  • The implementation of your method new returns self. The value of self there is the class TestClassB because new is a class method and self in a class method is the class itself.

    You should return the object that got created by sending super new:

    new
       |instance|
       instance := super new.
       InstanceCounter isNil
           ifTrue: [InstanceCounter := 0] 
           ifFalse: [InstanceCounter := InstanceCounter + 1].
       ^instance
    

    or shorter:

    new
        InstanceCounter isNil
           ifTrue: [InstanceCounter := 0] 
           ifFalse: [InstanceCounter := InstanceCounter + 1].
       ^super new