首先来看这段代码:
class Test
def method_public
puts "In method_public"
end
def method_protected
puts "In method_protected"
end
def method_private
puts "In method_private"
end
protected :method_protected
private :method_private
end
test=Test.new
分别尝试:
test.method_public
输出:In method_public
test.method_protected
输出:test.rb:20: protected method `method_protected' called for #<Test:0x3756068> (NoMethodError)
test.method_private
输出:test.rb:21: private method `method_private' called for #<Test:0x346070> (NoMethodError)
可知:public能被实例对象调用,protected和private不能被实例对象直接调用。
改写代码:
class Test
def method_public
puts "In method_public"
end
def method_protected
puts "In method_protected"
end
def method_private
puts "In method_private"
end
protected :method_protected
private :method_private
def access_method
puts method_public
puts method_protected
puts method_private
end
end
test = Test.new
test.access_method
输出:
In method_public
nil
In method_protected
nil
In method_private
nil
可知:三种方式都能被定义它们的类访问。
改写代码:
class Test
def method_public
puts "In method_public"
end
def method_protected
puts "In method_protected"
end
def method_private
puts "In method_private"
end
protected :method_protected
private :method_private
end
class SonTest < Test
def access_method
puts method_public
puts method_protected
puts method_private
end
end
test = SonTest.new
test.access_method
输出:
In method_public
nil
In method_protected
nil
In method_private
nil
可知:三种方法都能被定义它们的类的子类访问。
改写代码:
class Test
def method_public
puts "In method_public"
end
def method_protected
puts "In method_protected"
end
def method_private
puts "In method_private"
end
protected :method_protected
private :method_private
def call_method_protected(testmember)
puts testmember.method_protected
end
def call_method_private(testmember)
puts testmember.method_private
end
end
test1 = Test.new
test2 = Test.new
分别尝试:
test2.call_method_protected(test1)
输出:
In method_protected
nil
test2.call_method_private(test1)
输出:test.rb:21:in `call_method_private': private method `method_private' called for #<Test:0x36c5af4> (NoMethodError)
可知:protected方法可以被其他的实例对象访问,而private方法只能被自己的实例对象访问。
总结一下
- public方法可以被定义它的类和子类访问,并可以被类和子类的实例对象调用;
- protected方法可以被定义它的类和子类访问,不能被类和子类的实例对象调用,但可以被该类和子类的实例对象(所有)访问;
- private方法可以被定义它的类和子类访问,不能被类和子类的实例对象调用,且实例对象只能访问自己的private方法。
以上的陈述中,请注意“调用”和“访问”的区别。
---------------------
作者:阿迪达拉参上
来源:CSDN
原文:https://blog.csdn.net/adidala/article/details/23858501
版权声明:本文为博主原创文章,转载请附上博文链接!