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方法,可以被定义它的类和其子类访问,私有方法不能指定对象。
本文深入探讨了Ruby中public、protected及private方法的区别与使用场景。public方法可在类及其子类中自由访问;protected方法允许在类及子类内部使用,但不能通过实例对象直接调用;private方法仅能在定义它的类及子类中使用,不允许指定对象调用。
1万+

被折叠的 条评论
为什么被折叠?



