Ruby | Method overriding
Last Updated :
23 Nov, 2022
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 :
Ruby
class A
def a
puts 'Geeks'
end
end
class B < A
def a
puts 'Welcome to GeeksForGeeks'
end
end
b = B . new
b.a
|
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 :
Ruby
class Box
def initialize(width, height)
@w , @h = width, height
end
def getArea
@w * @h
end
end
class BigBox < Box
def getArea
@area = @w * @h
puts "Big box area is :
end
end
box = BigBox. new ( 15 , 20 )
box.getArea()
|
Output:
Big box area is : 300
In above example, The method getArea in class BigBox overrides the method getArea in class Box.
Share your thoughts in the comments
Please Login to comment...