Adding a new method to an existing interface traditionally has been a problem in Java because all implementations must be updated to include the new method or else a compile error will result. In Java 8, the new method can be declared as a default method in the interface and implementation logic can be provided in the interface itself. Therefore, existing implementations of the interface will continue to work successfully.
To understand how to use default methods in Java 8, follow these 15 steps.
UseArithmeticInterface, contains the main method that will test the interface implementation. The main method instantiates the interface implementation at line 3 and then calls the add method in the implementation class. The second class is the implementation class,
ArithmeticInterfaceImpl, and is defined at line 7. This class provides an implementation for the add method.
ArightmeticInterface.javain your editor and add the subtract method signature after the add method:
ArightmeticInterface.javain your editor and modify the subtract method by adding the default keyword and method logic: