Method Overriding in Ruby: Definition and Examples
method overriding happens when a subclass provides its own version of a method that is already defined in its parent class. This allows the subclass to change or extend the behavior of that method while keeping the same method name.How It Works
Method overriding in Ruby works like a child changing a rule set by their parent. Imagine a family recipe passed down from parent to child. The child can decide to tweak the recipe to their taste while keeping the original name. Similarly, a subclass inherits methods from its parent class but can replace a method with its own version.
When Ruby runs a method on an object, it first looks for that method in the object's class. If the method is overridden in the subclass, Ruby uses that version instead of the parent's. This lets subclasses customize or improve behaviors without changing the original parent class.
Example
This example shows a parent class Animal with a method sound. The subclass Dog overrides sound to give a different message.
class Animal def sound "Some generic sound" end end class Dog < Animal def sound "Bark" end end animal = Animal.new dog = Dog.new puts animal.sound puts dog.sound
When to Use
Use method overriding when you want a subclass to behave differently from its parent for a specific method. This is common in real-world programming where you have a general class and more specific subclasses.
For example, in a game, you might have a Character class with a method attack. Different character types like Wizard or Warrior can override attack to perform unique actions.
Key Points
- Method overriding lets subclasses replace parent class methods.
- It uses the same method name but changes behavior.
- It helps customize or extend functionality in object-oriented design.
- Ruby looks for the method in the subclass first when called.