Java Reference
In-Depth Information
Using the Java.extend() Method
Nashorn provides a better way to extend a class and implement multiple interfaces using
the Java.extend() method. In the Java.extend() method, you can pass maximum one
class type and multiple interface types. It returns a type that combines all passed in types.
You need to use the previously discussed anonymous class-like syntax to provide the
implementation for the abstract methods of the new type or override the existing method
of the types being extended. The following snippet of code uses the Java.extend()
method to implement the Calculator interface:
// Get the Calculator interface type
var Calculator = Java.type("com.jdojo.script.Calculator");
// Get a type that extends the Calculator type
var CalculatorExtender = Java.extend(Calculator);
// Implement the abstract methods in CalculatorExtender
// using an anonymous class like syntax
var calc = new CalculatorExtender() {
add: (function (n1, n2) n1 + n2),
subtract: (function (n1, n2) n1 - n2),
multiply: (function (n1, n2) n1 * n2),
divide: (function (n1, n2) n1 / n2)
};
// Use the instance of teh Calculator interface
var x = 15.0, y = 10.0;
var addResult = calc.add(x, y);
var subResult = calc.subtract(x, y);
var mulResult = calc.multiply(x, y);
var divResult = calc.divide(x, y);
printf("calc.add(%.2f, %.2f) = %.2f", x, y, addResult);
printf("calc.subtract(%.2f, %.2f) = %.2f", x, y, subResult);
printf("calc.multiply(%.2f, %.2f) = %.2f", x, y, mulResult);
printf("calc.divide(%.2f, %.2f) = %.2f", x, y, divResult);
calc.add(15.00, 10.00) = 25.00
calc.subtract(15.00, 10.00) = 5.00
calc.multiply(15.00, 10.00) = 150.00
calc.divide(15.00, 10.00) = 1.50
 
Search WWH ::




Custom Search