[quote]
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. [/quote]
[quote="《The Ruby Way》中第21页"]private意味着方法只可被当前类或其子类使用,只能通过“函数形式”调用——隐式或显式地将self作为接收方。protected意味着方法只能在当前类中调用,但与private不同,调用时可将非self指定为接收方。[/quote]
[b]protected主要是用于这种情况:想让某个类的一个实例与该类的另一个实例协作完成某些任务。[/b]
这时候,如果这个类的 name 不想让外部访问,就必须设置成 protected
如果是 private 的话,== 方法中的 o.name 就不能调用。
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. [/quote]
[quote="《The Ruby Way》中第21页"]private意味着方法只可被当前类或其子类使用,只能通过“函数形式”调用——隐式或显式地将self作为接收方。protected意味着方法只能在当前类中调用,但与private不同,调用时可将非self指定为接收方。[/quote]
[b]protected主要是用于这种情况:想让某个类的一个实例与该类的另一个实例协作完成某些任务。[/b]
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 就不能调用。