I am trying to access a class variable in one of my classes in Smalltalk.
I have two classes: Class1 and Class2.
Class1 has the following variables: year month day hour minute. Class2 has the following variables: start-time end-time. In the initialize method for Class2 I have the following:
start-time := Class1 new.
end-time := Class1 new.
Now I want to assign the year 2012 to start-time, how do I access the year variable in the Class1 object start-time?
Since you are sending new
message to the classes I will assume that you are interested in instance variables, and not class variables (shared variables) (see Pharo Object Model in Updated Pharo By Example to understand the differences).
In Pharo all class/instance variables are private, thus the way to access them is to create accessors.
Add to your Class1 methods
Class1>>year
^ year
Class1>>year: aYear
year := aYear
And then you can send the message to the class with the appropriate value:
Class2>>initialize
startTime := Class1 new.
startTime year: 2012.
"or by using a cascade"
startTime := Class1 new
year: 2012;
yourself.
If for whatever reason you needed to access a variable without accessors, you can use metaprogramming:
startTime instVarNamed: #year "meta-getter"
startTime instVarNamed: #year put: 2012 "meta-setter"
Finally, 'start-time'
is not a valid variable name.