Ruby 为您提供了三个级别的实例方法保护,分别是 public、private 或 protected。
Public 方法: Public 方法可被任意对象调用。默认情况下,方法都是 public 的,除了 initialize 方法总是 private 的。
Private 方法: 不能从外部访问,但是可以在类里面(或子类)用类方法访问,不能被类的对象调用(比如self.fun);
Protected 方法: 不能从外部访问,但是可以在类里面(或子类)用类方法访问,能被类的对象调用(比如self.fun),这里的调用只针对在类里面;
NOTE:private个protected都不能从外部访问,也就是不能实例化一个类,然后用类点函数来访问!
代码演示:pub.rb
class Student
Version = 2
@@student_counts = 0
attr_accessor :name, :no, :sex
def initialize(name, no, sex)
@name = name
@no = no
@sex = sex
end
def self.clazz_fun
puts "This is a class method"
end
class << self
def clazz_cun_2
puts "This is a class method which the second way to write"
end
def clazz_fun_3
puts "This is a class method which the third way to write"
end
end
def pub_fun
puts "This is the common way #{@name}, #{self.no}, #{@sex}"
pro_fun
puts "the protected way can be called in this common way"
pri_fun
puts "the privated way can be called in this common way"
end
public :pub_fun
def pro_fun
puts "This is a procted way"
end
protected :pro_fun
def pri_fun
puts "This is a privated way"
end
private :pri_fun
end
Student.clazz_fun
s = Student.new("young", 24, "hanzi")
s.pub_fun
puts "---------------------------"
class Student
def test
self.pro_fun
self.pub_fun
# self.pri_fun ERROR: pub.rb:60:in `test': private method `pri_fun' called for #<Student:0x00007f45990838c0 @name="young", @no=24, @sex="hanzi"> (NoMethodError) Did you mean? pro_fun
end
end
s.test
puts "+++++++++++++++++++++++++++++"
class MiddleStudent < Student
def sub_fun
pub_fun
pro_fun
pri_fun
puts "1111111111111111111111"
self.pub_fun
self.pro_fun
# self.pri_fun ERROR: pub.rb:76:in `sub_fun': private method `pri_fun' called for #<MiddleStudent:0x00007f71c8bc64e8> (NoMethodError) Did you mean? pro_fun
end
end
MiddleStudent.clazz_fun
ms = MiddleStudent.new("yooy", 10, "girl")
ms.sub_fun
执行ruby pub.rb
结果:
分析结果:
在59行,我们可以看到,直接self.pri_fun
,会报错,是因为:虽然这里依然是在类里面,但是self.
就代表这是类的对象,我们上面说的是,private不能被类的对象调用,所以报错, 而58行的self.pub_fun
没有报错,是因为在类里面,protect的方法可以被类的对象调用~
76行的报错也同理。