Chapter 2. Classes and Objects

Importing Classes

Import statements behave the same as in the Java™ programming language. The syntax is:

import PackageName.ClassName;
and
import PackageName.*;

If import statements are present, they must appear before any other application code. The JavaFX™ Script programming language defines its own namespace for its built-in library classes (packages javafx.*), but standard Java programming language classes can also be imported:

import javafx.application.*;
import java.lang.System;

...

Defining Classes

The syntax for specifying a class is the class keyword followed by the class name, optionally the extends keyword, and a comma separated list of the names of base classes, an open curly brace, a list of attributes and functions that each end in a semicolon, and a closing curly brace.

The JavaFX Script programming language supports multiple inheritance, and therefore, defines some new terminology and rules:

  • A plain class is any class that directly or indirectly extends a class written in the Java programming language.
  • A compound class is any class that is not a plain class.
  • By default, classes written in the JavaFX Script programming language are compound classses.
  • Classes can extend, at most, one plain class. If it does extend a plain class, it becomes a plain class. A class can also extend any number of compound classes, or Java programming language interfaces.

Note: A plain class is currently translated into a Java class, while a compound class is translated to a Java class and a Java interface.

It is possible to declare a class to as public, which means that it can be accessed from any script. Otherwise, the class can only be accessed from the containing script (this the default.)

The JavaFX Script programming language does not support constructors; you must use object literals instead. To mimic the behavior of a constructor, define a static function that returns a new object, and invoke that function.

Defining Objects

As described in the previous chapter, the preferred way to instantiate a class is with an object literal. This form of object allocation uses a declarative syntax consisting of the name of the class followed by a curly brace delimited list of attribute initializers. Each initializer consists of the attribute name followed by a colon, followed by an expression that defines its value. However, it is also possible to use the new keyword when creating an object:

import java.io.File;

var tmpPath = "/home/users/docs/tmp.txt"
var myFile = new File("tmp.txt");