重點(diǎn)關(guān)注private與protected
public
默認(rèn)即為public,全局都可以訪問(wèn),這個(gè)不解釋
private
C++, “private” 意為 “private to this class”, 但是Ruby中意為 “private to this instance”.
意思是:C++中,對(duì)于類(lèi)A,只要能訪問(wèn)類(lèi)A,就能訪問(wèn)A的對(duì)象的private方法。
Ruby中,卻不行:你只能在你本對(duì)象的實(shí)例中訪問(wèn)本對(duì)象的private方法。
因?yàn)镽uby的原則是“private意為你不能指定方法接收者”,接收者只能是self,且self必須省略!
所以Ruby中子類(lèi)可以訪問(wèn)父類(lèi)的private方法。但self.private_method是錯(cuò)的。
protected
可以在本類(lèi)或子類(lèi)中訪問(wèn),不能在其它類(lèi)中訪問(wèn)。
測(cè)試代碼(public均可訪問(wèn),代碼略)
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
注:ruby的訪問(wèn)控制不同于java,沒(méi)有包的區(qū)別。
其它包中的類(lèi)只要引用目標(biāo)類(lèi),和目標(biāo)類(lèi)同包下類(lèi)訪問(wèn)控制規(guī)則相同。
您可能感興趣的文章:- asp.net 修飾符介紹(關(guān)于public、private、protected、internal)
- 深入理解C++中public、protected及private用法
- C++中的三種繼承public,protected,private詳細(xì)解析
- 淺析php面向?qū)ο髉ublic private protected 訪問(wèn)修飾符
- JS中的public和private對(duì)象,即static修飾符
- C++友元(Friend)用法實(shí)例簡(jiǎn)介
- C++中的friend友元函數(shù)詳細(xì)解析
- 概述C++中的 public protected private friend關(guān)鍵字的用法