Course of Raku / Objects, I/O, and exceptions / Classes and objects

Classes

So far, the data types you have used — numbers, strings, arrays, and so on — were all built into Raku. Object-oriented programming lets you define your own types, called classes, and create values of those types, called objects.

A class is defined with the class keyword, followed by a name and a block:

class Dog {
}

This Dog class is empty for now, but it is already a new type. To create an object of the class — an instance — call the new method on the class name:

class Dog {
}

my $rex = Dog.new;
say $rex; # Dog.new

The variable $rex now holds a Dog object. Every call to new creates a separate object:

my $rex = Dog.new;
my $fido = Dog.new;

$rex and $fido are two distinct dogs, even though the class has no contents yet. In the following sections you will give a class its own data (attributes) and its own behaviour (methods). The first topic looks more closely at the difference between a class and its instances.

Also in this section

Practice

Complete the quiz that covers the contents of this section.

Exercises

This section contains 2 exercises. Examine all the topics of this section before doing the coding practice.

  1. Defined or not
  2. Name the type

Course navigation

Classes and objects   |   Type objects and instances