`

What's the difference between private and protected methods?

    博客分类:
  • Ruby
阅读更多
引用

In Ruby, private visibility is what protected was in Java. However, you can't have
truly private methods in Ruby; you can't completely hide a method.


《The Ruby Way》中第21页 写道
private意味着方法只可被当前类或其子类使用,只能通过“函数形式”调用——隐式或显式地将self作为接收方。protected意味着方法只能在当前类中调用,但与private不同,调用时可将非self指定为接收方。


protected主要是用于这种情况:想让某个类的一个实例与该类的另一个实例协作完成某些任务。

class O

  def initialize(name)
    @name = name
  end

  def ==(o)
    @name == o.name
  end

  protected

  def name
    @name
  end
end

o1 = O.new('name1')
o1.name # NoMethodError: protected method called
o2 = O.new('name2')
o1 == o2 # false


这时候,如果这个类的 name 不想让外部访问,就必须设置成 protected

如果是 private 的话,== 方法中的 o.name 就不能调用。
分享到:
评论

相关推荐

    java面试题英文版及其答案

    Public methods (getters and setters) are then provided to manipulate these private members, ensuring data integrity and controlling the interaction with the object's internal state. 9. What are the ...

    UE(官方下载)

    Did you know that you can not only change what is on UltraEdit's toolbars, you can also change the icon used, as well as create your own custom toolbars and tools? File tabs Understand how file tabs ...

    Java邮件开发Fundamentals of the JavaMail API

    Before looking into the JavaMail API specifics, let's step back and take a look at the protocols used with the API. There are basically four that you'll come to know and love: * SMTP * POP * IMAP...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. ...

Global site tag (gtag.js) - Google Analytics