How do private methods in interfaces work (Java 9)

In Java 9, interfaces can contain private methods. This enhancement allows code reuse within the interface, thus simplifying the implementation of default methods. Private methods in interfaces cannot be accessed by classes that implement the interface or by other interfaces. They are useful for containing shared code that multiple default methods can utilize without exposing that code externally.

Private methods are defined using the private access modifier and are used to provide common functionality to other methods within the interface.

    interface MyInterface {
        // Private method in interface
        private void commonHelper() {
            System.out.println("Common Helper Method");
        }

        default void methodA() {
            System.out.println("Method A");
            commonHelper(); // Calling the private method
        }

        default void methodB() {
            System.out.println("Method B");
            commonHelper(); // Calling the private method
        }
    }

    class MyClass implements MyInterface {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.methodA();
            obj.methodB();
        }
    }
    

Java 9 private methods interfaces default methods code reuse