Home »
Ruby Tutorial
Ruby Method Overriding
By IncludeHelp Last updated : December 01, 2024
What is Method Overriding in Ruby?
Method overriding simply means that there are two methods defined within the same scope and they both are used for performing different tasks. This feature is provided in an Object-oriented language which supports Inheritance. Inheritance is nothing but a mechanism through which the child class object can access the methods of the superclass. In Method overriding, two same name methods are present in the base class as well as in derived class but with different functionality. Overriding takes place in the manner that the method of derived class or subclass replaces or overrides the implementation of Derived class method.
Syntax
The general view of method overriding looks like,
class Parent
def Method
end
end
class Child
def Method
end
end
You can observe that name of both the methods is the same.
Demonstrating Method Overriding with Example
Now, let us understand how they differ in functionality with the help of an example:
=begin
Ruby program to demonstrate method overriding
=end
class Parent
def prnt
for i in 0..5
puts "Parent class method"
end
end
end
class Child < Parent
def prnt
for i in 0..5
puts "Child class method"
end
end
end
ob1 = Child.new # class instantiation
ob1.prnt
Output
Child class method
Child class method
Child class method
Child class method
Child class method
Child class method
You can observe in the above code that both the child and parent class method has the same name but are used for different purposes.
Another Example of Method Overriding
Go through the example given below to understand the concept in a broader way,
=begin
Ruby program to demonstrate method overriding.
=end
class Dollar
def initialize
puts "Enter amount in dollar"
@dlr = gets.chomp.to_f
end
def rupee
puts "#{@dlr}$ = #{71.23 * @dlr} INR"
end
end
class Yen < Dollar
def initialize
puts "Enter amount in Yen"
@yn = gets.chomp.to_f
end
def rupee
puts "#{@yn} Yen = #{0.67 * @yn} INR"
end
end
ob1 = Dollar.new
ob1.rupee
ob2 = Yen.new
ob2.rupee
Output
Run 1:
Enter amount in dollar
12
12.0$ = 854.76 inr
Enter amount in Yen
900
900.0Yen = 603.0 inr
Run 2:
Enter amount in dollar
190.23
190.23$ = 13550.0829 inr
Enter amount in Yen
890.23
890.23 Yen = 596.4541 inr
The above code has two methods with the same name 'rupees'. This is the case of method overriding where same name methods can exist in both child class and superclass. Here we are creating objects of child class and parent class and they are invoking their methods. If only child class object has created, then it must have replaced the parent class method. Remember that you can not override the private methods.