Design decisions: Why and when to make an interface private?

Jon picture Jon · Jan 1, 2011 · Viewed 16.2k times · Source

Are private interfaces ever used in design decisions ? If so, what are the reasons and when do you know the need for a private interface?

Answer

Andy Thomas picture Andy Thomas · Oct 28, 2015

A top-level interface cannot be private. It can only have public or package access. From the Java Language Specification, section 9.1.1: "Interface Modifiers":

The access modifiers protected and private pertain only to member interfaces whose declarations are directly enclosed by a class declaration (§8.5.1).

A nested interface can be private whenever it and its subclasses, if any, are an implementation detail of its top-level class.

For example, the nested interface CLibrary below is used as an implementation detail of the top-level class. It's used purely to define an API for JNA, communicated by the interface's Class.

public class ProcessController {
    private interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary( "c", CLibrary.class );
        int getpid();
    }

    public static int getPid() {
        return CLibrary.INSTANCE.getpid();
    }
}

As another example, this private interface defines an API used by private nested classes implementing custom formatting symbols.

public class FooFormatter {
    private interface IFormatPart { 
        /** Formats a part of Foo, or text.
         * @param foo Non-null foo object, which may be used as input.
         */
        void write( Foo foo ) throws IOException;
    }

    private class FormatSymbol implements IFormatPart { ... }

    private class FormatText implements IFormatPart { ... }

    ...
 }