0
0
Rubyprogramming~5 mins

Method overriding in Ruby

Choose your learning style9 modes available
Introduction

Method overriding lets you change how a method works in a child class while keeping the same method name. It helps customize behavior easily.

You want a child class to do something different from its parent class for the same action.
You have a general method in a parent class but need specific details in child classes.
You want to reuse code but change only parts of it in subclasses.
You want to improve or fix a method without changing the parent class.
Syntax
Ruby
class Parent
  def greet
    puts "Hello from Parent"
  end
end

class Child < Parent
  def greet
    puts "Hello from Child"
  end
end

The child class uses the same method name as the parent.

The child method replaces the parent method when called on a child object.

Examples
The Dog class changes the sound method to print "Bark" instead of "Some sound".
Ruby
class Animal
  def sound
    puts "Some sound"
  end
end

class Dog < Animal
  def sound
    puts "Bark"
  end
end
The Car class overrides start to give a more specific message.
Ruby
class Vehicle
  def start
    puts "Starting vehicle"
  end
end

class Car < Vehicle
  def start
    puts "Starting car engine"
  end
end
Sample Program

This program shows how the child class changes the greet method output.

Ruby
class Parent
  def greet
    puts "Hello from Parent"
  end
end

class Child < Parent
  def greet
    puts "Hello from Child"
  end
end

parent = Parent.new
child = Child.new

parent.greet
child.greet
OutputSuccess
Important Notes

If you want to call the parent method inside the child method, use super.

Overriding only works if the method names are exactly the same.

Summary

Method overriding lets child classes change parent class methods.

It uses the same method name in the child class.

It helps customize behavior without rewriting all code.