end aPeople = People.new("jimmy");#創(chuàng)建一個People的實例 puts aPeople.to_string #調用to_string方法 #puts aPeople.get_name_size #將報錯,因為該方法受保護 #puts aPeople.test #將報錯,因為該方法是私有方法 aPeople.show_name puts aPeople.name aPeople.name = "楊俊明" #修改姓名 aPeople.show_name #再定義一個子類 class Man People def initialize(_name) super @sex = true end
attr_reader:sex #定義只讀屬性sex
def call_protected_method puts get_name_size #調用父類的受保護方法 end
def call_protected_method2(man1) puts man1.get_name_size #注意這里:這里可以把父類的受保護方法,動態(tài)添加到子類實例 end
def call_private_method #子類可以調用父類的私有方法!!! 這一點剛開始很不習慣 test end
def call_private_method2(man1) man1.test #注意這里:語法檢查雖然可以通過,但是運行時會提示私有方法無法調用,這也是private與protected的區(qū)別 end
end puts "******************************" aMan = Man.new("jimmy.yang"); aMan.show_name aMan.call_protected_method puts aMan.sex aMan.call_private_method aMan2 = Man.new("Mike") aMan.call_protected_method2(aMan2); #aMan.call_private_method2(aMan2); a = "abc"; #aMan.call_protected_method2(a); #雖然ruby本身對變量沒有類型概念,但是這樣卻不行,即:在調用父類的受保護方法時,其實是要類型匹配的 puts aMan.class #顯示aMan的類名稱
運行結果如下:
復制代碼 代碼如下:
>ruby classDemo.rb My name is jimmy private method(test) in People. name = jimmy jimmy private method(test) in People. name = 楊俊明 ****************************** private method(test) in People. name = jimmy.yang 10 true private method(test) in People. 4 Man >Exit code: 0