I am trying to access a class variable in one of my classes in Smalltalk.
Are you sure that you want Class variables in this case? A Class variable (or attribute is held once and only once. It is accessible to all the instances of that Class, and all the instances of all it's sub-classes, as well as being accessible to the sub-classes themselves.
If what you want is to spawn many of the objects, each noting a different time, or startTime and endTime, then you need to use the more ordinary instance variables.
If however, you want to store one time, and only one-time, then yes, you can store the information in the Class itself.
I have two classes: Class1 and Class2.
I'll call Class1 "Time" and I'll call Class2 "StartEndTime"
Time has the following variables: year month day hour minute
. StartEndTime
has the following variables: startTime endTime
. In the initialize method for StartEndTime
I have the following:
startTime := Time new.
endTime := Time new.
Now I want to assign the year 2012 to startTime, how do I access the year variable in the object startTime?
The convention is to name getter accessor methods with the same name as the attribute. In which case the Time object instances will have a year
getter method, which returns the year of the Time object.
startTime year
would then return the variable named year
Similarly, setter accessor methods have the same name as their attribute, but are suffixed with a ':
'
startTime year: 2012
would then set the variable named year
to 2012
.
Putting these into an initialize
method would mean:
StartEndTime >> initialize
"Returns an initialized StartEndTime"
startTime := Time new.
endTime := Time new.
^self
Time >> year: anInt
"Returns receiver with its year set to the year argument."
year := anInt.
^self
In the Workspace (or Playground)
"create a new StartEndTime instanceobject"
aStartEndTime := StartEndTime new initialize.
aStartEndTime startTime: 2012.