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

Attributes

An empty class is not very useful. To let an object carry its own data, you give the class attributes. An attribute is declared inside the class with the has keyword:

class Dog {
    has $.name;
    has $.age;
}

Each object of the class gets its own copy of these attributes. You set their values when you create the object, by passing them to new as named arguments:

class Dog {
    has $.name;
    has $.age;
}

my $rex = Dog.new(name => 'Rex', age => 3);

The $. in has $.name does two things at once: it declares an attribute, and it creates a method of the same name — an accessor — that returns the attribute’s value:

say $rex.name; # Rex
say $rex.age;  # 3

Different objects hold their own values, independently of one another:

my $rex  = Dog.new(name => 'Rex',  age => 3);
my $fido = Dog.new(name => 'Fido', age => 5);

say $rex.name;  # Rex
say $fido.name; # Fido

The following topics show how to make attributes changeable and how to give them default values. (There is also a way to declare private attributes, hidden from the outside; we return to it once methods are introduced.)

Topics in this section

Practice

Complete the quiz that covers the contents of this section.

Exercises

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

  1. A point class
  2. A counter
  3. A book
  4. A changeable label

Course navigation

Solution: Name the type   |   Read-write attributes