2

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 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Instance Variables are variables which are the ones whose data varies with each instance of the object.

Class variables are those which are shared across all instances of a class. Actually every instance points to the same value and change is seen across all the class instances.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.