What is the difference between private and protected methods?
What is the difference between private and protected methods?
In Ruby, the distinction between private and protected methods revolves around their accessibility concerning object instances and inheritance. Both private and protected methods are used to control access to methods within a class, but they differ in how they can be called, especially in relation to the receiver of the method call.
Private methods in Ruby are restricted in their accessibility. They cannot be called with an explicit receiver, not even with self
. This means that private methods can only be called within the context of the current object; you cannot specify an object when calling these methods. They are intended for use only within the class in which they are defined and by subclasses, but only through methods that do not explicitly specify the receiver.
For example:
class Example
def public_method
private_method
end
private
def private_method
puts "I'm a private method"
end
end
example = Example.new
example.public_method # This will work
example.private_method # This will raise a NoMethodError
In this example, private_method
is called within public_method
without specifying a receiver, which is permissible. However, attempting to call private_method
directly on an instance of Example
will result in an error[1][2][3].
Protected methods are similar to private methods in that they cannot be accessed from outside the class or its subclasses, except when used within the context of the same class or a subclass. The key difference is that protected methods can be called with an explicit receiver, but only if the receiver is self
or an instance of the same class or its subclasses.
This al...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào