Course of Raku / Objects, I/O, and exceptions / Classes and objects
Inheritance
Inheritance lets one class build on another. A class
declared with is after its name inherits the attributes and
methods of the class it names — its parent (or base)
class.
class Animal {
has $.name;
method speak {
'some sound';
}
}
class Dog is Animal {
}Dog is Animal means a Dog is a kind of
Animal. Without writing anything new, Dog
already has the name attribute and the speak
method from Animal:
my $rex = Dog.new(name => 'Rex');
say $rex.name; # Rex
say $rex.speak; # some soundA Dog object is also recognised as an
Animal:
say Dog.new ~~ Animal; # TrueThe smart-match ~~ against a type is true when the
object is of that type or inherits from it. The next topic shows how a
child class can replace an inherited method with its own version.
Also in this section
Practice
Complete the quiz that covers the contents of this section.
Exercises
This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.