I understand that this question has been raised many times already. But I can't find the complete guide about all those kinds of variables. I've found a couple of articles that compare class variables vs class instance variables, but what about instance variables?
So, what is the difference between: instance variables, class variables and class instance variables? What kind of variables are inheritable and what are not?
2 Answers
An instance variable is, well, a variable that belongs to one specific object (aka instance). Inheritance is irrelevant in this case, since objects can't inherit from anything, only classes can.
Class instance variables don't exist. Classes are objects just like any other, so they can have instance variables just like any other object. When a class has an instance variable, this is sometimes called a class instance variable, but it's just an instance variable. So, again, it can't be inherited.
Class variables are strange beasts. They are shared among
- the class itself
- all instances of the class
- all subclasses of the class
- all instances of all subclasses of the class
- all subclasses of all subclasses of the class
- all instances of all subclasses of all subclasses of the class
- … and so on …
They are really more like global variables, considering how widely they are shared.
You can call this sharing inheritance, but I don't think that's a useful term. There is no polymorphic dispatch, no message sending, no overriding.
In Ruby, the term inheritance really only makes sense with methods, not with variables.