Course of Raku / Objects, I/O, and exceptions / Classes and objects / Inheritance / Exercises / An inherited attribute
Solution: An inherited attribute
Here is a possible solution to the task.
Code
class Vehicle {
has $.wheels;
}
class Bike is Vehicle {
has $.wheels = 2;
}
class Car is Vehicle {
has $.wheels = 4;
}
say Bike.new.wheels;
say Car.new.wheels;🦋 You can find the source code in the file inherited-attribute.raku.
Output
2
4Comments
BikeandCarboth inherit thewheelsattribute (and its accessor) fromVehicle. Neither redeclares the attribute from scratch — they only give the inherited one a default value,2and4respectively.Because the default is baked into each class, you can create the objects with a plain
Bike.newandCar.new, and the inherited accessor reads the right number of wheels back.You can still pass the value explicitly, for example
Car.new(wheels => 3), and an explicit argument overrides the default. But since a bike or a car most likely already comes with its usual number of wheels, the defaults keep the common case simple while leaving room for the occasional exception.
Course navigation
← An inherited attribute | Roles →