Java Reference
In-Depth Information
Extending Java Classes Implementing Interfaces
JavaScript lets you extend Java classes and implement Java interfaces in JavaScript. The
following sections describe different ways of achieving this.
Using a Script Object
You need to create a script object that contains implementations of the methods of the
interface and pass it to the constructor of the Java interface using the new operator. In
Java, an interface does not have a constructor and it cannot be used with the new operator,
except when creating an anonymous class. However, JavaScript lets you do that.
In Chapter 5, we had created the Calculator interface with four abstract methods.
The code for the interface is shown again in Listing 6-2 for your reference.
Listing 6-2. The Calculator Interface in Java
// Calculator.java
package com.jdojo.script;
public interface Calculator {
double add (double n1, double n2);
double subtract (double n1, double n2);
double multiply (double n1, double n2);
double divide (double n1, double n2);
}
In Chapter 5, we have created a calculator JavaScript object whose script is shown
again in Listing 6-3.
Listing 6-3. The Calculator Interface in Java
// calculator.js
// Create an object
var calculator = new Object();
// Add four methods to the prototype to the calculator object
calculator.add = function (n1, n2) n1 + n2;
calculator.subtract = function (n1, n2) n1 - n2;
calculator.multiply = function (n1, n2) n1 * n2;
calculator.divide = function (n1, n2) n1 / n2;
 
Search WWH ::




Custom Search