RubyRuby

Ruby public private protected

2017-08-22  本文已影响16人  就叫初九吧

public private protected 是定义在一个名为Module的类中的三个方法,限定了对方法的访问权限。

关键字 module class def 称为作用域门,出现这三个关键词时会发生作用域切换。

默认情况下 如果不声明,所有的方法都是public,在private 或者 protected后面都是private 或者 protected的方法。
同时也可以使用 public :demo, private :demo, protected :demo 的方式定义。

方法 initialize方法是private只能被new方法调用

  1. private 和 protected 方法不能在对象实例上直接调用
class Product
  def initialize(name)
      @name = name
  end
  def show
     @name
  end
  private
    def sku
        (1..5).to_a.join
    end
  protected
    def color
       'red'
    end
end
r_p1.png
  1. private 不能指定receiver 即使是self
    只能在方法中调用
  2. protected 在方法内部调用
    在方法中调用时可以指定 self
    在方法中相同类型的对象可以直接调用protected方法
  3. 在类的子类中 父类的private protected可以被调用但是仍旧遵循上面的规则

(参考一)[http://culttt.com/2015/06/03/the-difference-between-public-protected-and-private-methods-in-ruby/]
(参考二)[http://kaochenlong.com/2011/07/26/public-protected-and-private-method-in-ruby/]

上一篇下一篇

猜你喜欢

热点阅读