Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Ruby private method accessible in sub class?

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?

like image 371
Venkat Ch Avatar asked Jul 04 '15 06:07

Venkat Ch


1 Answers

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

like image 81
Sourabh Upadhyay Avatar answered Oct 22 '22 02:10

Sourabh Upadhyay