A class is a declaration of a constructor of objects with a specific type. Each object has zero or more attributes (instance variables) with zero or more behaviours (methods), that are defined inside a specific class or inherited from super-classes.
The attributes of a class can be either specified as parameters, or declared with the has keyword.
classExample(a, b) { has c =3 has d = a+c}var obj =Example(1,2)say obj.a #=> 1say obj.b #=> 2say obj.c #=> 3say obj.d #=> 4
Class initialization
Extra object-initialization setup can be done by defining a method named init, which will be called automatically called whenever a new instance-object is created.
classExample (a, b) { has r =0 method init { # called automatically r = a+b } method foo { r }}var obj =Example(3,4)say obj.foo #=> 7
Class variables
The syntax ClassName!var_name can be used for defining, accessing or modifying a class variable.
classExample {Example!hidden ='secret'# global class variable method concat (str) { str +' '+Example!hidden }}var x =Example()var y =Example()say x.concat('foo') #=> 'foo secret'say y.concat('bar') #=> 'bar secret'Example!hidden ='public'# changing the class variablesay x.concat('foo') #=> 'foo public'say y.concat('bar') #=> 'bar public'
The modification of a class variable can be localized by prefixing the declaration with the local keyword:
local Example!hidden ='local value'
Class inheritance (experimental)
Inheritance of behaviors and attributes, by a given class, is declared with the < operator, followed by the name of the class from which the current class inherits: