Ruby | Method overriding

Method is a collection of statements that perform some specific task and return the result. Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, method of the corresponding class will be executed.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of method overriding
 
# define a class
class A  
  def a  
    puts 'Geeks'  
  end  
end  
 
# define a subclass  
class B < A  
 
  # change existing a method as follows
  def a  
    puts 'Welcome to GeeksForGeeks'  
  end  
end  
    
b = B.new  
b.a  

chevron_right


Output :

Welcome to GeeksForGeeks

In above Example, Execution of a on the object of A printed Geeks from the a method defined in the A class whereas, execution of a on the object of B printed Welcome to GeeksForGeeks from the a method defined in the B class. It is very useful because it prevents us from making methods with different names and remembering that all. The method a in class B overrides the method a in class A.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of method overriding
  
# define a class
class Box
   # constructor method
   def initialize(width, height)
      @w, @h = width, height
   end
   # instance method
   def getArea
      @w * @h
   end
end
  
# define a subclass
class BigBox < Box
  
   # change existing getArea method as follows
   def getArea
      @area = @w * @h
      puts "Big box area is : #@area"
   end
end
  
# create an object
box = BigBox.new(15, 20)
  
# print the area using overriden method.
box.getArea()

chevron_right


Output:

Big box area is : 300

In above example, The method getArea in class BigBox overrides the method getArea in class Box.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.