Private Methods in Interface in Java Example

Since java 9, we can able to add private methods and private static methods in interfaces.
These private methods will improve code re-usability inside interfaces. For example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.
Using private methods in interfaces have four rules :
  • The private interface method cannot be abstract.
  • A private method can be used only inside the interface.
  • A private static method can be used inside other static and non-static interface methods.
  • A private non-static method cannot be used inside private static methods.

Java 9 Private Interface Method Example

package net.javaguides.corejava.java9;

/**
 * Java 9 - private methods and private static method in interfaces
 * @author Ramesh fadatare
 *
 */
public class PrivateInterfaceMethod implements CustomInterface {

    @Override
    public void abstractMethod() {
        System.out.println("abstract Method implementation");
    }

    public static void main(String[] args) {
        CustomInterface customInterface = new PrivateInterfaceMethod();
        customInterface.defaultMethod();
        customInterface.abstractMethod();
        CustomInterface.staticMethod();
    }
}

interface CustomInterface {

    public abstract void abstractMethod();

    public
    default void defaultMethod() {
        privateMethod(); //private method inside default method
        privateStaticMethod(); //static method inside other non-static method
        System.out.println("default method");
    }

    public static void staticMethod() {
        privateStaticMethod(); //static method inside other static method
        System.out.println("static method");
    }

    private void privateMethod() {
        System.out.println("private method");
    }

    private static void privateStaticMethod() {
        System.out.println("private static method");
    }
}

Comments