国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 莆田市| 台东市| 广水市| 衡山县| 西吉县| 曲沃县| 吉木萨尔县| 越西县| 宿松县| 湖北省| 白银市| 都昌县| 香港| 镇平县| 和平区| 平山县| 江西省| 渭南市| 广宁县| 株洲县| 虞城县| 富宁县| 镇宁| 台山市| 沽源县| 台前县| 吉木萨尔县| 岑溪市| 保靖县| 石楼县| 海淀区| 平定县| 通化市| 明水县| 齐河县| 河西区| 兴安盟| 神农架林区| 武强县| 舞阳县| 恩平市|