Chapter 3. Attributes and Functions

Attributes

Attributes define the state of an object. They are declared using the attribute keyword followed by the attribute's name, a colon (optional), the attribute's type (optional) terminated with a semicolon.

attribute AttributeName : AttributeType  ;

It is possible to declare default values for attributes (which can later be overridden by values provided in object literals.) The initializers are evaluated in the order the attributes are specified in the class declaration in the context of the newly created object:

import java.lang.System;

class X {
     attribute a: Number = 10;
     attribute b: Number = -1;
}

var x = X { };
System.out.println(x.a); // prints 10.0
System.out.println(x.b); // prints -1.0

In the absence of explicit initialization, each attribute is assigned a reasonable default:

import java.lang.System;

class DefaultValuesDemo {
     attribute a: Number;
     attribute b: Integer;
     attribute c: Boolean;
     attribute d: String;
}

var demo = DefaultValuesDemo {};
System.out.println("Default Value: " + demo.a);
System.out.println("Default Value: " + demo.b);
System.out.println("Default Value: " + demo.c);
System.out.println("Default Value: " + demo.d);

The above prints the following default values to the screen. (Note: The last line prints an empty string.)

Default Value: 0.0
Default Value: 0
Default Value: false
Default Value: 

Data types are covered in Chapter 4.

Functions

Functions define the behavior of an object. A function takes the following form:

function name (parameterName : parameterType, ...): returnType body

where body can be any expression.

Functions are first-class objects (they can, for example, be assigned to variables, or passed as parameters to other functions.)

Chapter one presented a simple example, defining a grow function that accepts no arguments and returns no values:

...

function grow(): Void {
     grow(1);
}

...

The demo also provided an overloaded version that allowed the user to specify a particular size:


...

function grow(amount: Integer): Void {
     width += amount;
     height += amount;
}

...

Functions can also be anonymous. Anonymous functions are often used to assign behavior to the action attribute of a GUI component:


// in GUI 

...

action: function() {
     System.out.println("Click!");
}

...