Ruby Inheritance
Inheritance lets one class take the methods of another class. The class that takes them can add its own methods and replace one it took.
Methods taken as they are
Dog adds no methods of its own. The new call and the greet call both use methods taken from Animal.
class Animal
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
class Dog < Animal
end
dog = Dog.new("Rex")
dog.greetAn override replaces a method
Dog writes greet again with its own words. The dog uses the new version, and the animal keeps the parent version.
class Animal
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
class Dog < Animal
def greet
puts "#{@name} says woof"
end
end
animal = Animal.new("Milo")
dog = Dog.new("Rex")
animal.greet
dog.greetsuper hands a value up
Dog initialize takes a name and a breed. super hands the name to the initialize in Animal, and Dog stores the breed.
class Animal
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
class Dog < Animal
def initialize(name, breed)
super(name)
@breed = breed
end
def profile
puts "#{@name} is a #{@breed}"
end
end
dog = Dog.new("Rex", "Labrador")
dog.greet
dog.profileExample
class Animal
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
class Dog < Animal
def initialize(name, breed)
super(name)
@breed = breed
end
def greet
puts "#{@name} says woof"
end
def profile
puts "#{@name} is a #{@breed}"
end
def fetch
puts "#{@name} fetches the ball"
end
end
animal = Animal.new("Milo")
dog = Dog.new("Rex", "Labrador")
animal.greet
dog.greet
dog.profile
dog.fetchKey points
- The parent class gives its methods to the child class.
- class Dog < Animal makes Dog a child of Animal.
- A child object can call a parent method with no change.
- A child can add methods that the parent does not have.
- A method written again in the child replaces the parent version for child objects.
- super in initialize hands its values to the initialize of the parent.
In this example, super hands the name to Animal initialize, and Dog stores its breed. Dog replaces greet with its own line. profile and fetch are extra methods that only Dog has. The animal object still uses the greet line from Animal.
Note
A child class names one parent only.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does super(name) do inside the initialize of Dog?