Jon*_*Jon 14 java private interface design-decisions
私有接口是否曾用于设计决策?如果是这样,原因是什么,何时知道需要私有接口?
一个顶级接口不能是私有的。它只能public访问或打包访问。根据Java语言规范的第9.1.1节:“接口修饰符”:
访问修饰符protected和private仅适用于其声明直接由类声明(第8.5.1节)括起来的成员接口。
甲嵌套接口可以是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();
}
}
Run Code Online (Sandbox Code Playgroud)
作为另一个示例,此私有接口定义由实现自定义格式符号的私有嵌套类使用的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 { ... }
...
}
Run Code Online (Sandbox Code Playgroud)
恕我直言,您无法有效地将接口设为私有。
然而,我经常有两个接口,一个用于公共使用,一个用于内部使用。如果可能的话,我将内部使用接口制作为本地包,例如
public interface MyInterface {
public void publicMethod();
}
interface DirectMyInterface extends MyInterface {
public void internalUseOnlyMethod();
}
Run Code Online (Sandbox Code Playgroud)
内部使用方法公开了我不希望其他开发人员使用和/或我希望能够轻松更改的方法。我拥有该接口的原因是我有几个想要通过接口在内部使用的实现。
| 归档时间: |
|
| 查看次数: |
12499 次 |
| 最近记录: |