我是Smalltalk(VisualAge环境)中的新成员,我尝试创建一个计算她的实例数的类。不幸的是,当我重写'新'方法时,某些东西不能工作。这是我的类代码:如何在Smalltalk中创建一个类的实例?
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.
! !
我想用 'initWithNiceParameter' 消息新的对象:
TestClassB initWithNiceParameter: 'my super string'
但我得到的是错误:
TestClassB does not understand niceVariable:
这是因为'TestClassB'也是一个对象,似乎它没有'niceVariable'setter。
当'新'方法被忽略时,您是否有任何想法如何创建对象?
虽然我们正在改进,让我们初始化InstanceCounter在零端#初始化并完全删除分支;) – 2014-10-03 16:12:27
将'TestClassB allInstances大小'不够? – 2014-10-03 17:17:47
@SeanDeNigris你的意思是#initialize和删除分支?我创建了这个方法(它与#new一样是类方法),它重写了Object类中的#initialize,但它不会通过创建新对象来自动调用。 – user3452568 2014-10-06 10:20:17