重點關注private與protected
public
默認即為public,全局都可以訪問,這個不解釋
private
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" endend 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 endend class C def test a = A.new #a.protected_mth #wrong #a.private_mth #wrong endend A.new.testB.new.testC.new.test
注:ruby的訪問控制不同于java,沒有包的區別。
其它包中的類只要引用目標類,和目標類同包下類訪問控制規則相同。
新聞熱點
疑難解答
圖片精選