Can anyone tell me about the difference between class variables and class instance variables?
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
Class variables are shared across all objects while instance variables are for data unique to each instance. Instance variable overrides the Class variables having same name which can accidentally introduce bugs or surprising behaviour in our code.
A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.
What is the difference between class variables and class instance variables? The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.
A class variable (@@
) is shared among the class and all of its descendants. A class instance variable (@
) is not shared by the class's descendants.
Class variable (@@
)
Let's have a class Foo with a class variable @@i
, and accessors for reading and writing @@i
:
class Foo @@i = 1 def self.i @@i end def self.i=(value) @@i = value end end
And a derived class:
class Bar < Foo end
We see that Foo and Bar have the same value for @@i
:
p Foo.i # => 1 p Bar.i # => 1
And changing @@i
in one changes it in both:
Bar.i = 2 p Foo.i # => 2 p Bar.i # => 2
Class instance variable (@
)
Let's make a simple class with a class instance variable @i
and accessors for reading and writing @i
:
class Foo @i = 1 def self.i @i end def self.i=(value) @i = value end end
And a derived class:
class Bar < Foo end
We see that although Bar inherits the accessors for @i
, it does not inherit @i
itself:
p Foo.i # => 1 p Bar.i # => nil
We can set Bar's @i
without affecting Foo's @i
:
Bar.i = 2 p Foo.i # => 1 p Bar.i # => 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With