what is method overriding in rails

 

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

Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5