Thursday, March 15, 2007

Instance variables and object state

Information and data associated with a particular object is called the state of the object.
我们应该能够做到:set/reset and read the state of an object。


The instance variable enables individual objects to remember state. Instance variables work much like other variables: You assign values to them, and you read those values back.
However,instance variables have a few differences.
1, Instance variable names always start with @. This enables you to recognize an instance variable at a glance.
2, Instance variables are only visible to the object to which they belong.
3, An instance variable is initialized in one method definition, inside a particular class.

Instance这个词意味着什么呢?意味着class instance,也就是object。所以,instance variable是和class没有关系的,只和一个具体的object有关系。
根据上面的第三条描述,一个instance variable是在一个class的method中初始化的。所以 ,在定义一个class的时候,写在method里面的才是instance varialbe,才能够被每个instance所使用。
但是,一个class本身也是一个object,所以,在method之外的variable就是该class这个object本身自己的instance variable了,与这个class的instance们没有关系。

Unlike a local variable, the instance variable @ivar retains the value assigned to it even after the method in which it was initialized has terminated. This property of instance variables—their survival across method calls—makes them suitable for maintaining state in an object.

我们常常要把arguments赋给Instance Variable。我对自己的编程要求是: Instance Varialbe的名字必须与argument的名字一样,例如:@word = word

No comments: