Focus on private and protected
Public
The default is public, the global can be accessed, this does not explain
Private
C + +, "private" means "private to this class", but Ruby is the "private to this instance".
In C + +, for Class A, you can access the private method of A's object as long as you can access Class A.
Ruby, but not: You can only access this object's private method in the instance of your object.
Because Ruby's principle is "private means you cannot specify a method recipient," the receiver can only be self, and self must omit!
So the Ruby Neutron class can access the private method of the parent class. But Self.private_method is wrong.
Protected
can be accessed in this class or subclass, and not in other classes.
Test code (accessible by public, slightly code)
Class A
def Test
protected_mth
private_mth
self.protected_mth
#self. private_mth #wrong
obj = b.new
obj.protected_mth
#obj. private_mth #wrong
end
protected
def protected_mth
puts "#{self.class}-protected"
end
private
def private_mth
puts "#{ Self.class}-private "End"
class B < A
def Test
protected_mth
private_mth
self.protected_mth
#self. private_mth #wrong
obj = b.new
obj.protected_mth
#obj. Private_ MTH #wrong
end
class C
def test
a = A.new
#a. protected_mth #wrong
#a. private_mth #wrong
end
a.new.test
b.new.test
c.new.test
Note: Ruby's access control is different from Java, and there is no packet difference.
Classes in other packages simply reference the target class and are the same as the class access control rules under the target-like package.