Method Visibility in Ruby
Last Updated :
06 Mar, 2020
Method visibility in Ruby refers that instance methods can be public, private or protected. Methods are by default public unless they are explicitly declared private or protected. Method visibility is used in Ruby to achieve Data Abstraction i.e showing only required information and hiding the background details.
Method visibility depends on the three types of access modifiers of a class in Ruby:
Public Access Modifier
Protected Access Modifier
Private Access Modifier
Public Access Modifier
The methods of a class which are public are easily called from any part of the program.
Example :#1
class Geeks
def publicMethod1
puts "publicMethod1 called!"
end
public
def publicMethod2
puts "publicMethod2 called!"
end
end
obj = Geeks. new ()
obj.publicMethod1()
obj.publicMethod2()
|
Output:
publicMethod1 called!
publicMethod2 called!
In the above, program two public methods publicMethod1()
and publicMethod2()
of the class Geeks
are called.
Protected Access Modifier
The methods of a class which are declared protected can only be called from the class in which it is declared and the classes derived from it.
Example :#2
class Parent
protected
def protectedMethod
puts "protectedMethod called!"
end
end
class Geeks < Parent
def publicMethod
self .protectedMethod
end
end
obj = Geeks. new
obj.publicMethod
|
Output:
protectedMethod called!
In the above program, the protectedMethod()
of Parent
class is not accessible directly, so it is called from the publicMethod()
of the derived class Geeks
.
Private Access Modifier
The methods of a class which are declared private are called within the class only, private access modifier is the most secure access modifier.
Example :#3
class Geeks
private
def privateMethod
puts "privateMethod called!"
end
public
def publicMethod
privateMethod
end
end
obj = Geeks. new
obj.publicMethod
|
Output:
privateMethod called!
In the above program, the privateMethod()
of the Geeks
class an not be called directly. So it is called from the publicMethod()
of the class Geeks
.
Now let us look at another program which demonstrates Method Visibility.
Example :#4
class Parent
private
def privateMethod
puts "privateMethod called!"
end
protected
def protectedMethod
puts "protectedMethod called!"
end
public
def publicMethod1
puts "publicMethod1 called!"
end
def publicMethod2
protectedMethod
privateMethod
end
end
class Child < Parent
def publicMethod3
protectedMethod
end
end
obj1 = Parent. new
obj2 = Child. new
puts "\nParent methods: \n"
obj1.publicMethod1
obj1.publicMethod2
puts "\nChild methods: \n"
obj2.publicMethod1
obj2.publicMethod3
|
Output:
Parent methods:
publicMethod1 called!
protectedMethod called!
privateMethod called!
Child methods:
publicMethod1 called!
protectedMethod called!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...