Home » Ruby programming

Ruby Method Overriding

Method overriding in Ruby: Here, we are going to learn about the method overriding in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 17, 2019

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.

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. 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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.