Static Fields and Functions in JavaFX

26 03 2010

A static field or method is one that is accessible via the class itself without the need for an instance of the class. Constants, such as the number of months in a year, or methods that perform calculations that don’t require access to any instance fields are examples of cases where static fields and methods should be used. Java has had static fields and methods since its inception. JavaFX used to have static fields and functions, but no longer does. They have been replaced with script level variables and script level functions. A script level variable or function is declared outside of the class definition and behaves pretty much like static fields and methods in Java.

Here is an example of static fields and methods in Java in a file called TimeTools.java:

public class TimeTools {

    public final static int MONTHS_IN_YEAR = 12;

    public static int yearsToMonths(int years) {
        return years * MONTHS_IN_YEAR;
    }

    public static void main(String[] args) {
        int years  = 5;
        System.out.println("Since there are "
          + TimeTools.MONTHS_IN_YEAR
          + " months in a year, there are "
          + TimeTools.yearsToMonths(years)
          + " months in " + years + " years.");
    }
}

In this case the TimeTools prefix wasn’t needed because the main method was in the TimeTools class, but it would be needed if the field or method were being accessed from a method in another class.

And here’s the equivalent in JavaFX Script in a file named TimeTools.fx:

public class TimeTools {
}

public def MONTHS_IN_YEAR = 12;

public function yearsToMonths(years:Integer):Integer {
    return years * MONTHS_IN_YEAR;
}

function run() {
    var years  = 5;
    var months = TimeTools.yearsToMonths(years);
    println("Since there are {TimeTools.MONTHS_IN_YEAR} months in "
            "a year, there are {months} months in {years} years.");
}

Notice that MONTHS_IN_YEAR and the yearsToMonths() function are both declared outside of the TimeTools class definition. If they were inside the class then an instance of TimeTools would be required in any place where they were going to be accessed.

Again, the TimeTools prefix is only needed from outside of this file.

So while there’s no longer a static keyword in JavaFX, the equivalent functionality can be achieved through script level variables and functions. Just remember to pull your fields and functions outside of the class definition and then use them like you did in Java.

Joshua Smith

Advertisements