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

心不动则不痛 提交于 2019-12-03 09:04:45

问题


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?


回答1:


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 { ... }

    ...
 }



回答2:


IMHO You cannot usefully make an interface private.

However I often have two interfaces, one for public use and one for internal use. The internal use interface I make package local if possible e.g.

public interface MyInterface {
   public void publicMethod();
}

interface DirectMyInterface extends MyInterface {
   public void internalUseOnlyMethod();
}

The internal use methods expose methods I don't want other developers to use and/or I want to be able to change easily. The reason I have the interface at all is that I have several implementations which I want to use internally via an interface.




回答3:


It has to be package protected if the interface if for internal use. In general if the interface hasn't any interest outside it's ambit it's a good api design decision to hide it because there's less complexity for the users of the interface and also allows you to refactor it more easily, because when the interface is public and in the API you loss the liberty to change it.



来源:https://stackoverflow.com/questions/4573713/design-decisions-why-and-when-to-make-an-interface-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!