Is Ruby private method accessible in sub class?

Venkat Ch picture Venkat Ch · Jul 4, 2015 · Viewed 8.3k times · Source

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?

Answer

Sourabh Upadhyay picture Sourabh Upadhyay · Jul 4, 2015

Here's a brief explanation from this source:

  1. Public methods can be called by anyone---there is no access control. Methods are public by default (except for initialize, which is always private).
  2. Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
  3. 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