Ruby中的public、protected和private(转帖)
Ruby中的public、protected和private
栗子1:
class Person
public
def my_public_method
'I am a public method'
end
protected
def my_protected_method
'I am a protected method'
end
private
def my_private_method
'I am a private method'
end
end
person1 = Person.new
尝试:
puts person1.my_public_method
输出:I am a public method
puts person1.my_protected_method
输出:main.rb:617:in `': protected method `my_protected_method' called for # (NoMethodError)
puts person1.my_private_method
输出:main.rb:618:in `': private method `my_private_method' called for #(NoMethodError)
得出:public能被实例对象调用,protected和private不能被实例对象直接调用
栗子2:
class Person
public
def my_public_method
'I am a public method'
end
def access_method
puts my_public_method
puts my_protected_method
puts my_private_method
end
protected
def my_protected_method
'I am a protected method'
end
private
def my_private_method
'I am a private method'
end
end
person1 = Person.new
person1.access_method
输出:
I am a public method
I am a protected method
I am a private method
得出:public、protected、private方法都可以被定义他们的类访问
栗子3:
class Person
public
def my_public_method
'I am a public method'
end
protected
def my_protected_method
'I am a protected method'
end
private
def my_private_method
'I am a private method'
end
end
class Man < Person
def access_method
puts my_public_method
puts my_protected_method
puts my_private_method
end
end
son = Man.new
son.access_method
输出:
I am a public method
I am a protected method
I am a private method
得出:public、protected、private方法都可以被定义他们的类的子类访问
栗子4:
class Person
public
def call_method_protected(testmember)
puts testmember.my_protected_method
end
def call_method_private(testmember)
puts testmember.my_private_method
end
def my_public_method
'I am a public method'
end
protected
def my_protected_method
'I am a protected method'
end
private
def my_private_method
'I am a private method'
end
end
person1 = Person.new
person2 = Person.new
尝试:
person2.call_method_protected(person1)
输出:
I am a protected method
person2.call_method_private(person1)
输出:
main.rb:720:in `call_method_private': private method `my_private_method' called for #(NoMethodError)
得出:protected方法可以被其他的实例对象访问,而private方法不可以。
总结:
public方法可以被定义它的类和子类访问,并可以被类和子类的实例对象调用;
protected方法可以被定义它的类和子类访问,不能被类和子类的实例对象调用,但可以被该类的实例对象(所有)访问;
private方法可以被定义它的类和子类访问,不能被类和子类的实例对象调用,只能在自身中调用私有方法。
作者:itxing
链接:https://www.jianshu.com/p/da8068deff89
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。