From: Martin DeMello Date: 2003-06-25T20:38:45+09:00 Subject: Re: protect parents from children Simon Strandgaard <0bz63fz3m1qt3001@sneakemail.com> wrote: > class A > def initialize > @value = [1, 2, 3] > end Okay, class A defines an instance variable @value and initializes it to [1,2,3]. > attr_reader :value > def selftest > if @value.size == 3 > puts "OK" > else > puts "Watch out, we have been modified" > p @value > end > end > end and tests to see if @value has changed since its initialization. > class B < A B inherits from A, and therefore inherits the methods initialize and test, which have not been overridden, and the instance variable @value. > def test1 > objs = value > objs << 4 > selftest > end > def test2 > @value = [5, 6] > selftest > end > end and adds two new methods, available to objects of class B, but not of class A. However, the terms 'parent' and 'child' refer to classes, whereas @value is an instance variable. You're modifying an object of class B, which contains an attribute @value that B just happens to have inherited from its superclass, A. The values of instance variables are part of the object, not the class. Furthermore, the whole point of inheritance is that you can override methods defined in the base class, so in that sense, a base class can and usually does change the bits it inherited from the parent (which is not the same thing as changing the parent). martin