设计决策中是否使用过私有接口?如果是这样,原因是什么?您什么时候知道需要私有接口?
A 顶层接口不能是私有的。它只能有public
或包访问。来自Java 语言规范,第 9.1.1 节:“接口修饰符” https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.1.1:
访问修饰符 protected 和 private 仅适用于其声明直接包含在类声明中的成员接口(第 8.5.1 节)。
A 嵌套接口 can be private
每当它及其子类(如果有)是其顶级类的实现细节.
例如,嵌套接口CLibrary
下面用作顶级类的实现细节。它纯粹用于定义 JNA 的 API,通过接口的通信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();
}
}
作为另一个示例,此私有接口定义了实现自定义格式化符号的私有嵌套类所使用的 API。
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 { ... }
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)