Ruby學習筆記_public,protected,private

class Person
	def speak
		" protected:speak "
	end
	def laugh
	" private:laugh"
	end
	
	protected :speak
	private   :laugh
	
	def useLaugh(another)
		puts another.laugh #這裏錯誤,私有方法不能指定對象
	end
	
	def useSpeak(another)
		puts another.speak
	end
end

class Student<Person
	def useLaugh
		puts laugh
	end
	
	def useSpeak
		puts speak
	end
end

p1=Person.new
#p1.speak   實例對象不能訪問protected方法
#p1.laugh   實例對象不能訪問private方法

p2=Student.new
p2.useSpeak  #protected可以被定義它的類和其子類訪問
p2.useLaugh  #private可以被定義它的類和其子類訪問

puts "------------------"

p2=Person.new
p2.useSpeak(p1) # protected:speak
#p2.useLaugh(p1)


● public方法,可以被定義它的類和其子類訪問,可以被類和子類的實例對象調用;
● protected方法,可以被定義它的類和其子類訪問,不能被類和子類的實例對象直接調用,但是可以在類和子類中指定給實例對象;
● private方法,可以被定義它的類和其子類訪問,私有方法不能指定對象。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章