Call super class method in Nashorn Javascript (js) Engine in Java 8




Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Call super class method in javascript >

package nashornJs;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
*
* Call super class method in javascript
*
*/
public class MyNashornClass {
   public static void main(String[] args) throws Exception {
      System.out.println("In java - START");
      
      ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
       engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");    
       System.out.println("In java - FINISH");
      
   }
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
1)  Call super class method
Draw shape
Draw square shape
2) Another way of doing above
Draw shape
Draw square shape
End myNashornJavaScript.js
In java - FINISH


*/

ShapeSuperClass.java
package nashornJs;
/**
*
*/
public class ShapeSuperClass{
   public void draw() {
       System.out.println("Draw shape");
   }
}



E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
// 1)  Call super class method
print('1)  Call super class method');
var superClass = Java.type('nashornJs.ShapeSuperClass');
var subClass = Java.extend(superClass);
//Provide implementation of ShapeSuperClass
var squareSubClass = new subClass() {
   //Provide implementation of draw method
   draw: function() {
       Java.super(squareSubClass).draw(); //Call super class method
       print('Draw square shape');
   }
}
squareSubClass.draw();
//  2) Another way of doing above
print('2) Another way of doing above ');
var squareSubClass2 = Java.extend(superClass, {
   // Provide implementation of run method
   draw: function() {
       print('Draw square shape');
   }
});
var squareSubClassObject = new squareSubClass2();
Java.super(squareSubClassObject).draw(); //Call super class method
squareSubClassObject.draw();
print('End myNashornJavaScript.js');




Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

eEdit
Must read for you :