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.
Method overriding lets you change how a method works in a child class while keeping the same method name. It helps customize behavior easily.
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.
class Animal def sound puts "Some sound" end end class Dog < Animal def sound puts "Bark" end end
class Vehicle def start puts "Starting vehicle" end end class Car < Vehicle def start puts "Starting car engine" end end
This program shows how the child class changes the greet method output.
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
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.
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.
greet in a Ruby child class?def method_name followed by body and end. Multi-line with indentation is standard. Parentheses are optional, but def greet() puts ... end is valid syntax if properly formatted. Colon syntax is invalid.class Parent
def greet
puts 'Hello from Parent'
end
end
class Child < Parent
def greet
puts 'Hello from Child'
end
end
obj = Child.new
obj.greetgreet method of Parent with its own version.greet calls the Child's version, printing 'Hello from Child'.class Parent
def speak
puts 'Parent speaks'
end
end
class Child < Parent
def speak()
puts 'Child speaks'
end
end keyword to finish the class definition.speak is correctly named and defined; parentheses are allowed but optional.end for Child class -> Option Dend [OK]end keywords carefully [OK]class Animal
def sound
'Some sound'
end
end
class Dog < Animal
def sound
super + ' and Bark'
end
end
class Cat < Animal
def sound
super + ' and Meow'
end
end
puts Dog.new.sound
puts Cat.new.soundsuper in overridden methodssound and call super to get Animal's sound return value.Pass the test and this pattern moves unknown