Ruby 中 Private 和 Protected 方法的区别

/

Ruby 中 Private 和 Protected 方法的区别是一个小知识点,总结归纳一下。

class Father
  def method_a
    puts self.method_private
  end

  def method_b
    puts method_private
  end

  def method_c
    puts self.method_protected
  end

  def method_d
    puts method_protected
  end

  private
  def method_private
    puts "I am method PRIVATE in #{self.class}"
  end

  protected
  def method_protected
    puts "I am method PROTECTED in #{self.class}"
  end
end

class Son < Father
  def son_method_private
    method_private
  end

  def son_method_protected
    method_protected
  end
end

father = Father.new
son = Son.new

Private 和 Protected 方法不能在对象中直接调用,只能在对象的上下文中间接调用,对于对象来说,Private 和 Protected 方法是不透明的。其中,Private 方法只能在对象的上下文中被 Self 隐式调用。

father.method_private
=> NoMethodError

father.method_protected
=> NoMethodError

father.method_a
=> NoMethodError

father.method_b
=> I am method PRIVATE in Father

father.method_c
=> I am method PROTECTED in Father

father.method_d
=> I am method PROTECTED in Father

Private 和 Protected 方法可以被子类继承,子类可以调用并覆盖父类的 Private 和 Protected 方法。

son.son_method_private
=> I am method PRIVATE in Son

son.son_method_protected
=> I am method PROTECTED in Son

Private 和 Protected 方法可以通过 send 调用

father.send(:method_private)
=> I am method PRIVATE in Father

father.send(:method_protected)
=> I am method PROTECTED in Father

Comments