Types, classes & roles
Inheritance
FullDerive a class with is, and override methods in the subclass.
A class inherits from another with is. The subclass gains the parent's attributes and methods, and may override any method by declaring one of the same name.
Subclass and override #
class Animal {
method speak { "..." }
}
class Dog is Animal {
method speak { "Woof" }
}
say Dog.new.speak;
Output
WoofDog inherits from Animal but replaces speak, so Dog.new.speak is Woof.
Calling the overridden method #
An override can still reach the method it replaced. callsame runs the next candidate up the inheritance chain — the parent's version — so a subclass can extend behaviour rather than discard it.
class Animal { method describe { "an animal" } }
class Dog is Animal {
method describe { callsame() ~ " that barks" }
}
say Dog.new.describe;
Output
an animal that barksNotes #
callsameis one of a small family (nextsame,callwith,nextwith,samewith) for invoking the next candidate — see Re-dispatch. You can also name the parent explicitly withself.Animal::describe.- Raku supports multiple inheritance (
is A is B), but composing roles is usually the better tool for sharing behaviour — see Roles. - Every class ultimately inherits from
Mu(viaAny), which is where universal methods like.WHATand.definedcome from.