“私有”,“公开”和“受保护的方法”之间有什么区别? [英] What are the differences between "private", "public", and "protected methods"?
问题描述
我正在学习Ruby,结果使我感到困惑。
I'm learning Ruby, and have come up to a point where I am confused.
我正在使用的书是在谈论私有
,公共
和受保护的方法
,但我仍然有些困惑。两者之间有什么区别?
The book I am using is talking about private
, public
, and protected methods
, but I am still a bit confused. What are the differences between each?
推荐答案
公共-可以在任何地方调用
Public - can be called from anywhere
私有-无法在类范围之外调用该方法。对象只能将消息发送给自己
Private - The method cannot be called outside class scope. The object can only send the message to itself
例如:面包师将 bake
方法设置为公开,但 break_eggs
是私有的
ex: the baker has bake
method as public but break_eggs
is private
受保护的-只要默认对象可以调用对象的受保护方法 self
是与您要调用其方法的对象相同类的实例
Protected - You can call an object's protected methods as long as the default object self
is an instance of the same class as the object whose method you're calling
ex:其中 n
受保护的方法, c1
可以要求 c2
执行 c2.n
,因为 c1
和 c2
都是同一个实例class
ex: with n
protected method, c1
can ask c2
to execute c2.n
, because c1
and c2
are both instances of the same class
最后但并非最不重要:
- 继承:子类继承其父类的方法访问规则
- Inheritance: Subclasses inherit the method-access rules of their superclass
如果类D< C,则D将展示出与C实例相同的访问行为
if "class D < C", then D will exhibit the same access behaviour as instances of C
引用: http:// www.amazon.com/Ruby-Rails-Techniques-Developers/dp/1932394699
这篇关于“私有”,“公开”和“受保护的方法”之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!