Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book


Functions define behavior. They encapsulate statements that operate on inputs, function arguments, and may produce a result, a returned expression. Like variables, functions are either script functions or instance functions. Script functions operate at the script level and have access to variables and other functions defined at the script level. Instance functions define the behavior of an object and have access to the other instance variables and functions contained within the function’s declaring class. Furthermore, an instance function may access any script-level variables and functions contained within its own script file.

To declare a function, use an optional access modifier, public, protected, or package, followed by the keyword function and the function name. If no access modifier is provided, the function is private to the script file. Any function arguments are contained within parentheses. You may then specify a function return type. If the return type is omitted, the function return type is inferred from the last expression in the function expression block. The special return type of Void may be used to indicate that the function returns nothing.

In the following example, both function declarations are equal. The first function infers a return type of Glow, because the last expression in the function block is an object literal for a Glow object. The second function explicitly declares a return type of Glow, and uses the return keyword.

public function glow(level: Number) {
      // return type Glow inferred
      Glow { level: level };

public function glow(): Glow { // explicit return type
      return glow(3.0); // explicit return keyword

The return keyword is optional when used as the last expression in a function block. However, if you want to return immediately out of an if/else or loop, you must use an explicit return.

In JavaFX, functions are objects in and of themselves and may be assigned to variables. For example, to declare a function variable, assign a function to that variable, and then invoke the function through the variable.

var glowFunction : function(level:Number):Glow;
glowFunction = glow;

Functions definitions can also be anonymous. For example, for a function variable:

var glowFunction:function(level:Number): Glow =
    function(level:Number) {
        Glow { level: level };

Or, within an object literal declaration:

TextBox {
    columns: 20
    action: function() {
        println("TextBox action");

Use override to override a function from a superclass.

class MyClass {
      public function print() { println("MyClass"); }
class MySubClass extends MyClass {
      override function print() { println("MySubClass"); }
  • + Share This
  • 🔖 Save To Your Account