Ruby 中的方法可见性
Ruby 中的方法可见性是指实例方法可以是公共的、私有的或受保护的。默认情况下,方法是公共的,除非它们被明确声明为私有或受保护。 Ruby 中使用方法可见性来实现数据抽象,即仅显示所需信息并隐藏背景细节。
方法的可见性取决于 Ruby 中类的三种访问修饰符:
公共访问修饰符
公共类的方法很容易从程序的任何部分调用。
示例:#1
# program to illustrate public access modifier
# defining class
class Geeks
# methods are public by default
def publicMethod1
puts "publicMethod1 called!"
end
# using public keyword
public
def publicMethod2
puts "publicMethod2 called!"
end
end
# creating the object
obj = Geeks.new()
# calling methods
obj.publicMethod1()
obj.publicMethod2()
输出:
publicMethod1 called!
publicMethod2 called!
上面程序调用了Geeks
类的两个公共方法publicMethod1()
和publicMethod2()
。
受保护的访问修饰符
声明为受保护的类的方法只能从声明它的类及其派生的类中调用。
示例:#2
# program to illustrate protected access modifier
# super class
class Parent
# protected keyword
protected
# protected method
# can not be called directly
def protectedMethod
puts "protectedMethod called!"
end
end
# sub class
class Geeks < Parent
def publicMethod
# protected method called in public method
self.protectedMethod
end
end
# creating object
obj = Geeks.new
# calling method
obj.publicMethod
输出:
protectedMethod called!
在上面的程序中, Parent
类的protectedMethod()
是不能直接访问的,所以是从派生类Geeks
的publicMethod()
中调用的。
私有访问修饰符
声明为私有的类的方法只能在类中调用,私有访问修饰符是最安全的访问修饰符。
示例:#3
# program to illustrate private access modifier
# defining class
class Geeks
# private keyword
private
# private method
# can not be called directly
def privateMethod
puts "privateMethod called!"
end
# public keyword
public
# public method
def publicMethod
# private method called in public method
privateMethod
end
end
# creating object
obj = Geeks.new
# calling method
obj.publicMethod
输出:
privateMethod called!
在上述程序中, Geeks
类的privateMethod()
并没有被直接调用。所以它是从Geeks
类的publicMethod()
调用的。
现在让我们看另一个演示方法可见性的程序。
示例:#4
# program to illustrate Method Visibility
# super class
class Parent
private
# private method
def privateMethod
puts "privateMethod called!"
end
protected
# protected method
def protectedMethod
puts "protectedMethod called!"
end
public
# public methods
def publicMethod1
puts "publicMethod1 called!"
end
def publicMethod2
# protected method called in public method
protectedMethod
# private method called in public method
privateMethod
end
end
# sub class
class Child < Parent
# public method
def publicMethod3
# protected method called in public method
protectedMethod
end
end
# creating object
obj1 = Parent.new
obj2 = Child.new
# calling method
puts "\nParent methods: \n"
obj1.publicMethod1
obj1.publicMethod2
puts "\nChild methods: \n"
obj2.publicMethod1
obj2.publicMethod3
输出:
Parent methods:
publicMethod1 called!
protectedMethod called!
privateMethod called!
Child methods:
publicMethod1 called!
protectedMethod called!