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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.