1. Introduction
From Java 9, private
methods can be added to Java interfaces. In this tutorial, we’ll discuss the purpose of adding private methods in Java and how to define these methods in an interface.
2. Why private methods in Java interface?
Java 8 allowed interface to have methods with implementation logic. Such methods are called default methods.
Suppose there are few default methods in an interface. And all of these methods are having some common code. This will result in lot of duplicate code. The better approach would be to write the common code or implementation in a separate method. Since this logic is internal to the default method, it is better to keep such method as private
. From Java 9, you can create private methods in interface.
3. Defining private methods in Java 9
Let us understand private methods in Java 9 with an example.
interface Foo { default void calculate(int first, int second) { int sum = first + second; print(sum); } private void print(int value) { System.out.println("sum: " + value); } }
In this example, print
is the private
method being called from the default method calculate
.
A private method in interface can be defined as static as well. Let us see this with an example.
interface Foo { static void calculate(int first, int second) { int sum = first + second; print(sum); } private static void print(int value) { System.out.println("sum: " + value); } }
4. Benefits of private methods in interface
As discussed earlier, private methods are only visible to other methods in an interface. Since a private method is internal to an interface, it can be used to encapsulate the implementation logic and hide implementation details from the classes implementing the interface.
Another benefit of using private methods is that it reduces duplicate code. Multiple default or static methods in interface can keep duplicate code in a separate private method.
5. Conclusion
In this tutorial, we discussed the need, benefits and how to define private methods in a Java interface. This was a short tutorial but an important one. Hope this was helpful.
Happy learning!