I have code as follows:
class A
private
def p_method
puts "I'm a private method from A"
end
end
class B < A
def some_method
p_method
end
end
b = B.new
b.p_method # => Error: Private method can not be called
b.some_method # => I'm a private method from A
b.some_method
calls a private method that is defined in class A
. How can a private method be accessed in the class where it is inherited? Is this behavior the same in all object oriented programming languages? How does Ruby do encapsulation?
Here's a brief explanation from this source:
- Public methods can be called by anyone---there is no access control. Methods are public by default (except for initialize, which is always private).
- Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
- Private methods cannot be called with an explicit receiver. Because you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.
This answer from a similar question expands on the topic in more detail: https://stackoverflow.com/a/1565640/814591
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