ruby - Private method and encapsulation : Prevent accidental private method overriding -
i trying understand how encapsulation mechanism works in ruby :
class def public_method_a; p private_method; end; private def private_method; 'a'; end; end class b < def public_method_b; p private_method; end; private def private_method; 'b'; end; end
now when try run code, here :
1. > a.new.public_method_a => "a" 2. > b.new.public_method_b => "b" 3. > b.new.public_method_a => "b"
basically, third call refers private method defined in b , not in a. java developer's point of view, encapsulation violation. call private_method
should refer method defined in class call made. in ruby, seems more matter of context. right ?
how can make sure private methods never called outside respective class ? doing wrong ?
thank in advance help.
nutshell: private
means message can't have explicit receiver.
that's all; nothing more.
it removes message public api, nothing regarding subclasses , on.
protected
means instances , sub-class instances can call method, e.g., can't call outside inheritance tree.
note both trivially subverted via send
.
Comments
Post a Comment