| 1 | =head1 NAME |
|---|
| 2 | |
|---|
| 3 | Perl6::Overview::Object - Object-oriented Programming |
|---|
| 4 | |
|---|
| 5 | =head1 DESCRIPTION |
|---|
| 6 | |
|---|
| 7 | =head2 Basic class definition |
|---|
| 8 | |
|---|
| 9 | class ClassName { |
|---|
| 10 | has $.public_instance_var; |
|---|
| 11 | # Untyped instance variable, a read-only accessor is automatically |
|---|
| 12 | # generated. Methods have read-write access to $.instance_var. |
|---|
| 13 | |
|---|
| 14 | has $.public_instance_var is rw; |
|---|
| 15 | # Untyped instance variable, a read-write accessor is automatically |
|---|
| 16 | # generated. |
|---|
| 17 | |
|---|
| 18 | has Type $.public_instance_var; |
|---|
| 19 | # Typed instance variable. |
|---|
| 20 | |
|---|
| 21 | has $!private_instance_var; |
|---|
| 22 | # Private instance variable, no accessor is automatically generated. |
|---|
| 23 | } |
|---|
| 24 | |
|---|
| 25 | =head2 Inheritance |
|---|
| 26 | |
|---|
| 27 | class ParentClass {...} |
|---|
| 28 | |
|---|
| 29 | class SubClass is ParentClass {...} |
|---|
| 30 | # or |
|---|
| 31 | class SubClass { |
|---|
| 32 | is ParentClass; |
|---|
| 33 | ...; |
|---|
| 34 | } |
|---|
| 35 | |
|---|
| 36 | =head2 Methods |
|---|
| 37 | |
|---|
| 38 | method methodname(...) {...} |
|---|
| 39 | # Standard subroutine signature |
|---|
| 40 | |
|---|
| 41 | method methodname($invocant: ...) {...} |
|---|
| 42 | # The invocant (the class or the instance) is explicitly bound to |
|---|
| 43 | # $invocant. In any case, there's self and $?CLASS, too. |
|---|
| 44 | |
|---|
| 45 | method ^methodname(...) {...} |
|---|
| 46 | # Class method |
|---|
| 47 | |
|---|
| 48 | method methodname(::?CLASS $self: ...) {...} |
|---|
| 49 | # Instance method |
|---|
| 50 | |
|---|
| 51 | =head2 Roles |
|---|
| 52 | |
|---|
| 53 | role RoleName { |
|---|
| 54 | method methodname(...) {...} |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | class SomeClass does RoleName {...} |
|---|
| 58 | # or |
|---|
| 59 | class SomeClass { |
|---|
| 60 | does RoleName; |
|---|
| 61 | } |
|---|
| 62 | |
|---|
| 63 | =head2 Magical function |
|---|
| 64 | |
|---|
| 65 | self # Returns the current instance |
|---|
| 66 | |
|---|
| 67 | =head2 Magical variables |
|---|
| 68 | |
|---|
| 69 | $?CLASS # The current class as scalar variable |
|---|
| 70 | ::?CLASS # The current class as package variable |
|---|
| 71 | $?ROLE # The current role as scalar variable |
|---|
| 72 | ::?ROLE # The current role as package variable |
|---|
| 73 | |
|---|
| 74 | =head2 Subtypes |
|---|
| 75 | |
|---|
| 76 | my subtype Int::Odd of Int where { $^value % 2 == 1 }; |
|---|
| 77 | # Declaration of a new, lexical subtype of Int, allowing only odd integers. |
|---|
| 78 | |
|---|
| 79 | my Int::Odd $var = 3; # valid |
|---|
| 80 | $var++; # invalid |
|---|
| 81 | |
|---|
| 82 | my Int::Odd $var = 4; # invalid |
|---|