Course of Raku / Addendum 🆕 / Types and text machines / Objects and classes / Exercises / Animals that speak
Solution: Animals that speak
Here is a possible solution to the task.
Code
class Animal {
has $.name;
method speak { '...' }
method greet { "{$.name} says {self.speak}" }
}
class Dog is Animal { method speak { 'Woof' } }
class Cat is Animal { method speak { 'Meow' } }
for Dog.new(name => 'Rex'), Cat.new(name => 'Tom') -> $pet {
say $pet.greet;
}🦋 You can find the source code in the file animal-inheritance.raku.
Output
Rex says Woof
Tom says MeowComments
greetis defined once in the base class, but it callsself.speak. Becauseselfis the actual object, the call reaches the subclass’s ownspeak.This is polymorphism: the same
greetproducesWooffor a dog andMeowfor a cat without any conditional code.