Ruby私有方法是否可以在子类中访问?

时间:2023-01-15 20:30:16

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?

b.some_method调用在类A中定义的私有方法。如何在继承它的类中访问私有方法?在所有面向对象的编程语言中,这种行为是否相同? Ruby如何封装?

1 个解决方案

#1


7  

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. 任何人都可以调用公共方法---没有访问控制。默认情况下,方法是公共的(初始化除外,它始终是私有的)。

  3. Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
  4. 受保护的方法只能由定义类及其子类的对象调用。访问权归家庭所有。

  5. 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.
  6. 无法使用显式接收器调用私有方法。因为在使用它们时无法指定对象,所以只能在定义类中调用私有方法,并且可以在同一对象中调用直接后代。

This answer from a similar question expands on the topic in more detail: https://*.com/a/1565640/814591

来自类似问题的答案更详细地扩展了该主题:https://*.com/a/1565640/814591

#1


7  

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. 任何人都可以调用公共方法---没有访问控制。默认情况下,方法是公共的(初始化除外,它始终是私有的)。

  3. Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
  4. 受保护的方法只能由定义类及其子类的对象调用。访问权归家庭所有。

  5. 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.
  6. 无法使用显式接收器调用私有方法。因为在使用它们时无法指定对象,所以只能在定义类中调用私有方法,并且可以在同一对象中调用直接后代。

This answer from a similar question expands on the topic in more detail: https://*.com/a/1565640/814591

来自类似问题的答案更详细地扩展了该主题:https://*.com/a/1565640/814591