Focus on private and protected
Public
The default value is public, which can be accessed globally.
Private
C ++, "private" indicates "private to this class", but Ruby prefers "private to this instance ".
In C ++, As long as class A can access Class A, it can access the private method of the object of Class.
Ruby, but not: You can only access the private method of this object in your object instance.
Because the ruby principle is "private means you cannot specify the method receiver", the receiver can only be self, and self must be omitted!
Therefore, subclasses in Ruby can access the private method of the parent class. However, self. private_method is incorrect.
Protected
It can be accessed in this class or subclass and cannot be accessed in other classes.
Test code (public access, Code omitted)
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" endendclass 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 endendclass C def test a = A.new #a.protected_mth #wrong #a.private_mth #wrong endendA.new.testB.new.testC.new.test
Note: There is no package difference between Ruby access control and Java.
Classes in other packages only need to reference the target class, which is the same as the class access control rules in the same package.
Reference: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility