C++, “private” 意為 “private to this class”, 但是Ruby中意為 “private to this instance”.
意思是:C++中,對于類A,只要能訪問類A,就能訪問A的對象的private方法。
Ruby中,卻不行:你只能在你本對象的實例中訪問本對象的private方法。
因為Ruby的原則是“private意為你不能指定方法接收者”,接收者只能是self,且self必須省略!
所以Ruby中子類可以訪問父類的private方法。但self.private_method是錯的。
protected
可以在本類或子類中訪問,不能在其它類中訪問。
測試代碼(public均可訪問,代碼略)
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
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
end
class C
def test
a = A.new
#a.protected_mth #wrong
#a.private_mth #wrong
end
end
A.new.test
B.new.test
C.new.test