Messi
Messi

Reputation: 97

Inheritance and instance variable in Ruby

I know that instance variables have nothing to do with inheritance:

class A

  def initialize
    @x = 2
  end

end

class B < A

  def puts_x
    puts @x
   end

  def x=(value)
    @x = value
  end

end

b = B.new
b.puts_x
b.x=3
b.puts_x

This outputs:

2
3

Here, class B inherits from class A, and @x in class B has nothing to do with inheritance.

But the output is 2. I want to understand it.

The "Ruby Inheritance" page says:

Since instance variables have nothing to do with inheritance, it follows that an instance variable used by a subclass cannot "shadow" an instance variable in the super-class. If a subclass uses an instance variable with the same name as a variable used by one of its ancestors, it will overwrite the value of its ancestor's variable.

I also want any examples for this.

Upvotes: 1

Views: 1686

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

B inherits initialize from A.

At object creation, initialize is invoked. So you get @x set to 2 even for objects of class B.

I think, the sentences you are quoting refer to this scenario:

class A
  def initialize
    @x = 42
  end
end

class B < A
  def initialize
    @x = 23
  end
end

h = B.new

Now, h has just one instance variable @x with value 23. It is not like there is one @x from B and one from A. You can see this here:

class A
  def initialize
    @x = 42
  end

  def set_x_from_a
    @x = 12
  end

  def print_x_from_a
    puts @x
  end
end

class B < A
  def initialize
    @x = 23
  end

  def set_x_from_b
    @x = 9
  end

  def print_x_from_b
    puts @x
  end
end

h = B.new
h.print_x_from_a            # => 23
h.print_x_from_b            # => 23
h.set_x_from_a
h.print_x_from_b            # => 12
h.set_x_from_b
h.print_x_from_a            # => 9

Upvotes: 9

Related Questions