JavaFX Init Block Setting Default Values

26 06 2009


Introduction

To create default values in Java, an instance variable with a String data type we would often have null and empty string values by default. In JavaFX we can create default values the same, but also have the opportunity to determine if the instance variables have ever been initialized at all.  This is cool because you can ensure that values are valid before the values can be used. An example would be if you had a variable called distance which holds an Integer.  A distance could not be a negative so the init block implementer could ensure that anything less than zero will take on the value zero.  When using an init block, you can use JavaFX’s a built-in function called isInitialized(object:Object) located (javafx.lang.Builtins) to determine if the instance variable has been initialized.

public static boolean isInitialized(java.lang.Object varRef)

Example

In this example a class called Cat will have instance variables called name and age. The default values will be initialized inside of the init block after the instance variables get their values.

The Cat class’ requirements:

  • When the Cat is instantiated without values being set the values are considered null and not initialized. Name the cat ‘Felix’.
  • When the Cat is instantiated with values being set to null name the cat ‘Garfield’
  • When the Cat is instantiated with values being set to empty string name the cat ‘Tom’

Example

package initstuff;

/**
 * @author cdea
 */
class Cat {
    var name:String;
    init {

        // Default name setting when there are null or empty string values
        // Not initialized
        if (not isInitialized(name)){
            name = "Felix"
        } else {
            // Is initialized but with null or empty string as value
            if (name == null) {
                name = "Garfield"
            } else if (name.trim().equals("")){
                name = "Tom"
            }
        }
    } // init
}

var myCat = Cat{};
println("myCat's name is {myCat.name}");
var myCat2 = Cat{name:" "};
println("myCat2's name is {myCat2.name}");
var myCat3 = Cat{name:null};
println("myCat3's name is {myCat3.name}");

Output

myCat’s name is Felix
myCat2’s name is Tom
myCat3’s name is Garfield

Conclusion

This is very similar to constructors in Java, but in JavaFX you have a little more control of setting the values after values have been initialized. This will help prevent the user of the API to put invalid information when instantiating an object. Another example is that it ensures the values fall in a particular range.


Actions

Information

One response

16 07 2009
Java desktop links of the week, June 29 | Jonathan Giles

[...] post discusses the order in which init and postinit blocks are called,  the second post discusses how to set default values in init blocks, and finally the third post discusses implementing a presentation model in JavaFX using [...]

Leave a comment