Main Page

Previous Next

Native Methods

It is possible to include a method in a class that is implemented in some other programming language, such as C or C++, external to the Java Virtual Machine. To specify such a method within a class definition you use the keyword native in the declaration of the method. For example:

public native long getData();     // Declare a method that is not in Java

Of course the method will have no body in Java since it is defined elsewhere, where all the work is done, so the declaration ends with a semi-colon. The implementation of a native method will need to use an interface to the Java environment. The standard API for implementing native methods in C for example, is called JNI – the Java Native Interface.

The major drawback to using native methods in Java is that your program will no longer be portable. Security requirements for applets embedded in Web pages require that the code must all be written in Java – using native methods in an applet is simply not possible. Since the primary reasons for using Java are the portability of the code and the ability to produce applets, the need for you to add native methods to your Java programs will be minimal. We will, therefore, not delve any deeper into this topic.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor