#Ruby的访问控制
public方法,可以被定义它的类和其子类访问,可以被类和子类的实例对象调用
protected方法,可以被定义它的类和其子类访问,不能被类和子类的实例对象直接调用,但是可以在类和子类中指定给实例对象
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)
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)
#Ruby语言的访问控制是动态的,是在程序运行时刻确立的
#可以根据自己的需要,在程序的不同位置,改变某个方法的访问控制级别
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
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