Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between class variables and class instance variables?

Can anyone tell me about the difference between class variables and class instance variables?

like image 463
cmd Avatar asked Sep 27 '10 09:09

cmd


People also ask

What is the difference between a class variable and instance variable?

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.

What is the difference between class variables and instance variables in Python?

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.

What is the difference between class and instance class?

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 variable and instance variable in Ruby?

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.


1 Answers

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 
like image 92
Wayne Conrad Avatar answered Sep 28 '22 09:09

Wayne Conrad