Fork me on GitHub

Programming, Internet & more

Java 9 Private Interface Methods

This is another post about a new feature in Java 9. Today, we will talk about interfaces.

Private Interface Methods

Since Java 8 it is possible to use default methods in interfaces. These methods allowed us to implement functionality directly into an interface method. However, interface methods neededed to use one of the following visibility modifiers:

  • public
  • abstract
  • default
  • static

Please notice the absence of the private modifier. Since Java 9 it is now allowed to also use private methods in interfaces. Let’s take a look at this example:

public interface NumberCheck {

    public default boolean is42(int number) {
        if (isGreaterThan42(number) || isLessThan42(number)) {
            return false;
        }

        return true;
    }

    private boolean isGreaterThan42(int number) {
        return number > 42;
    }

    private boolean isLessThan42(int number) {
        return number < 42;
    }
}

The default method is42() makes use of the private helper methods to reduce the complexity of itself.

Why do we need private methods in interfaces?

Private interface methods become interesting while using them along with default methods. Before Java 9 it was possible to use default methods but eventually they become longer and longer and it was impossible to structure them properly. With Java 9 we can mainly see private methods as helper methods to split up default methods into several smaller ones like we would do with normal methods in classes.

What about static methods?

The rules of private methods also apply to private static methods. This means we can also use private static methods in interfaces:

public interface NumberCheck {

    public static boolean is42(int number) {
        if (isGreaterThan42(number) || isLessThan42(number)) {
            return false;
        }

        return true;
    }

    private static boolean isGreaterThan42(int number) {
        return number > 42;
    }

    private static boolean isLessThan42(int number) {
        return number < 42;
    }
}

Conclusion

Private interface methods are a great addition to the default methods introduced in Java 8. They play very well together and help to make code more structured and clean.

Category: java9

Leave a Reply

Your email address will not be published. Required fields are marked *