Ruby的訪問控制public、protected、private
#Ruby的訪問控制
public方法,可以被定義它的類和其子類訪問,可以被類和子類的實(shí)例對象調(diào)用
protected方法,可以被定義它的類和其子類訪問,不能被類和子類的實(shí)例對象直接調(diào)用,但是可以在類和子類中指定給實(shí)例對象
private方法,可以被定義它的類和其子類訪問,私有方法不能指定對象。- class Person
- def speak
- puts "protected:speak."
- end
- def laugh
- puts "private:laugh."
- end
- protected :speak
- private :laugh
-
- def useSpeak(another)
- another.speak
- end
- def useLaugh(another)
- another.laugh
- end
- end
- p1=Person.new
- p2=Person.new
- p2.useSpeak(p1) #protected:speak
- #p2.useLaugh(p1) #E6.5-1.rb:21:in `useLaugh': private method `laugh' called for #<Person:0xb47188> (NoMethodError)
- 復(fù)制代碼
復(fù)制代碼 #Ruby語言的訪問控制是動態(tài)的,是在程序運(yùn)行時(shí)刻確立的
#可以根據(jù)自己的需要,在程序的不同位置,改變某個(gè)方法的訪問控制級別- class Student
- def talk
- puts "i am a student."
- end
- private:talk
- end
- p=Student.new
- #p.talk #E6.5-1.rb:38:in `<main>': private method `talk' called for #<Student:0xb464b0> (NoMethodError)
- class Student
- public:talk
- end
- p=Student.new
- p.talk #i am a student
- 復(fù)制代碼
復(fù)制代碼 |