How to Use Static Methods with Java 8 Interfaces
Traditionally, interfaces in Java could not define static methods. In Java 8, however, static methods in interfaces are allowed. A static method stores Java logic and is not implemented by the implementation Java class. You might use a static method to return data meaningful to interface applications such as a list of product categories or a routing list of departments that should receive a report generated by the interface implementation. To learn how to use static methods in Java 8, follow these seven steps.
- First you will code the interface. In your text editor, type in the following Java statements:
The static method will return a routing list; a list of departments to which the report should be sent.
- Save your file as ReportInterface.java.
- Open a command prompt and navigate to the directory containing your Java interface. Then type in the command to compile the source and hit Enter.
- Now you will create the program that implements the interface and tests the implementation. Create a new file in your text editor. Type in the following Java statements:
This file contains two classes. The first class,
UseReportInterface, contains the main method that will test the interface implementation. The main method instantiates the interface implementation at line 3 and then calls the static method in order to obtain the routing list. Notice that when calling the static method the interface name (
ReportInterface) is used as the prefix to the method, as opposed to using the object name (
reportInterfaceImpl). Next, the main method calls the implementation methods to produce the report. The second class is the implementation class,
ReportInterfaceImpl, and is defined at line 15. This class provides minimalistic code for each interface method that in the real world would be replaced with Java statements to retrieve and format employee data from a database.
- Save your file as UseReportInterface.java.
- Return to the command prompt. Then type in the command to compile the source and hit Enter.
- Now type in the command to run your program and hit Enter. The output displays the routing list that was returned by the static method and the report produced by calling the implementation methods.