Java Reference
In-Depth Information
Object literal initialization
Another aspect of JavaFX class usage is object declaration. JavaFX supports object-literal-
declaration to initialize a new instance of the class. This format lets developers declaratively
create a new instance of a class using the class's literal representation and pass in property
literal values directly into the initialization block to the object's named public properties.
var vehicle = Vehicle {
year :2010
color : "Grey"
make :"Mini"
model :"Cooper"
The previous snippet declares variable vehicle and assigns to it a new instance of the
Vehicle class with year = 2010 , color = Grey , make = Mini , and model = Cooper .
The values that are passed in the literal block overwrite the default values of the named
public properties.
There's more...
JavaFX class definition mechanism does not support a constructor as in languages such as
Java and C#. However, to allow developers to hook into the life cycle of the object's instance
creation phase, JavaFX exposes a specialized code block called init{} to let developers
provide custom code which is executed during object initialization.
Initialization block
Code in the init block is executed as one of the final steps of object creation after properties
declared in the object literal are initialized. Developers can use this facility to initialize values
and initialize resources that the new object will need. To illustrate how this works, the previous
code snippet has been modified with an init block. You can get the full listing of the code at
ch01/source-code/src/javafx/Vehicle2.fx .
class Vehicle {
init {
color = "Black";
function drive () : Void {
println("You are driving a "
"{year} {color} {make} {model}!");
var vehicle = Vehicle {
Search WWH ::

Custom Search