Java Reference
In-Depth Information
How It Works
Using a Java interface in JavaScript can be beneficial for creating objects that adhere to
the implementation criteria. However, using interfaces in JavaScript is a bit different
than using them in a Java solution. For example, interfaces cannot be instantiated in
Java. This is not the case when using them in JavaScript; you must actually instantiate
an object of the interface type in order to use it.
The example demonstrates the implementation of an interface, PositionType ,
which is used for defining a number of methods within an employee position. The
methods are used for calculating an employee's hourly and yearly wage. To make use
of the PositionType interface from JavaScript, the new keyword is used to instan-
tiate an instance of that interface, assigning it to a JavaScript variable. When instantiat-
ing the interface, a JavaScript object is passed to the constructor. The object contains
implementations for each of the non-default methods within the interface by identify-
ing the name of the method, followed by the implementation. In the example, there is
only one method implemented on instantiation—it is identified as hourlyWage() . If
there had been more than one method implemented, the implementations would be sep-
arated by commas.
Although using Java interfaces is a bit different in JavaScript, they certainly
provide a benefit. In reality, they are performing the same task within JavaScript as
they are within Java. In Java, in order to implement an interface, you must create an
object that implements it. You do the same thing within JavaScript, except that in order
to create the implementing object, you must instantiate an instance of the interface.
18-9. Extending Java Classes
Problem
You want to extend a concrete Java class in your Nashorn JavaScript solution.
Solution
First obtain a reference to the Java class that is to be extended by calling the
Java.type() function within your JavaScript file. Then create the subclass by call-
ing on the Java.extend() function and passing the reference to the class that will
Search WWH ::




Custom Search