Attributes define the state of an object. They are declared using the attribute
keyword followed by the attribute's name, a colon, the attribute's type, optionally a cardinality specification ([]
meaning zero or more, terminated with a semicolon:
attribute AttributeName : AttributeType Cardinality ;
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 will be 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:
For for more information on these data types, see Chapter 4, Variables and Basic Data Types.
Functions define the behavior of an object. A function takes the 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 { width++; height++; } ...
The demo also provided an overloaded version allowing 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:
import java.lang.System; import javafx.ui.*; Frame { visible: true content: FlowPanel { content: Button { text: "Click Me!" action: function() { System.out.println("Click!"); } } } }