Close
Close

More with OOPs


In this chapter, you will learn about method overriding. It means to have methods with the same name in both superclass and subclass.

So, let's start learning.

Method overriding


Override means having two methods with the same name but doing different tasks. It means that one of the methods overrides the other.
If there is any method in the superclass and a method with the same name in its subclass, then by executing the method, method of the corresponding class will be executed.
Let's understand it with an example.

class Rectangle
  def initialize(length,breadth)
    @length = length
    @breadth = breadth
  end
  def getArea
    puts "#{@length*@breadth} is area of rectangle"
  end
end
class Square < Rectangle
  def initialize(side)
    super(side,side)
    @side=side
  end
  def getArea
    puts "#{@side*@side} is area of square"
  end
end
s = Square.new(4)
r = Rectangle.new(2,4)
s.getArea
r.getArea
Output
16 is area of square
8 is area of rectangle

In this example, the method from the coressponding class came into action, which means that one overrode the other.
Execution of 'getArea' on the object of Rectangle (r) printed "8 is area of rectangle" from the 'getArea' method defined in the Rectangle class whereas, execution of 'getArea' on the object of Square (s) printed "16 is area of square" from the 'getArea' method defined in the Square class.
It is very useful because it prevents us from making methods with different names and remembering that all.

There is not much to explain in this chapter. So, it is recommended to solve questions to get things clearer.

In theory, there is no big difference between theory and practice. But in practice, there is.
-Yogi Berra

Ask Yours
Post Yours
Doubt? Ask question