国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Ruby中的public、private、protected區(qū)別小結(jié)

2019-10-26 19:23:54
字體:
供稿:網(wǎng)友

重點關(guān)注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,沒有包的區(qū)別。
其它包中的類只要引用目標類,和目標類同包下類訪問控制規(guī)則相同。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 中方县| 砀山县| 鸡东县| 泽普县| 文成县| 扎兰屯市| 于田县| 天峨县| 威海市| 遂川县| 西昌市| 贵南县| 仁怀市| 城市| 庐江县| 珲春市| 精河县| 察哈| 陵水| 桐梓县| 郎溪县| 沧州市| 玉山县| 青龙| 叙永县| 台北县| 昌都县| 探索| 太谷县| 湛江市| 汝城县| 静宁县| 当雄县| 江口县| 衡阳市| 新沂市| 南城县| 休宁县| 广东省| 武定县| 古丈县|