【发布时间】:2013-06-05 09:24:27
【问题描述】:
我试图测试 private interfaces 的工作,并编写了下面的代码。我可以理解,如果我们不希望任何其他类实现它们,那么可能会出现声明 private interfaces 的情况,但是变量呢?接口变量隐式为public static final,因此即使接口被声明为私有,我也能够访问它们。这可以在下面的代码中看到。
public class PrivateInterfaceTest {
/**
* @param args
*/
public static void main(String[] args) {
TestingInterfaceClass test = new TestingInterfaceClass();
TestingInterfaceClass.inner innerTest = test.new inner();
System.out.println(innerTest.i);
}
}
class TestingInterfaceClass {
private interface InnerInterface {
int i = 0;
}
class inner implements InnerInterface {
}
}
这是否意味着我们永远无法真正拥有private interface?如果我们可以访问private interface 之外的变量,那么拥有private interface 真的有意义吗?
编辑: 只是想补充一下,如果我们有私有内部类,就不会出现同样的情况。内部类中的私有变量永远不会暴露。
【问题讨论】:
-
我认为所有这些代码都在同一个文件中?
-
是的,所有代码都在同一个文件中。
-
对我来说,私有接口根本没有意义,尽管可访问的 int 很奇怪。
-
一个接口被设计成一个公共合约,那么隐藏它的意义在哪里?
-
@joerx:如果您不希望自己的合同对全世界可见,那该怎么办?