java - 私有(private)接口(interface)中的变量

标签 java interface private

我正在尝试测试 private interfaces 的工作并编写了下面的代码。我可以理解,如果我们不希望任何其他类实现它们,可能会出现声明 private interfaces 的情况,但是变量呢?接口(interface)变量是隐式的 public static final,因此即使接口(interface)被声明为私有(private),我也能够访问它们。这可以在下面的代码中看到。

 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 真的有意义吗?

编辑: 只是想补充一点,如果我们有私有(private)内部类,就不会出现同样的情况。内部类中的私有(private)变量永远不会暴露。

最佳答案

您的成员(member)界面是私有(private)的。继承的静态字段不是私有(private)的。

私有(private)成员接口(interface)不能用作封闭顶级类或枚举之外的类型。这对于防止外部代码实现您可能希望更改的接口(interface)很有用。来自 JLS:

The access modifiers protected and private pertain only to member interfaces within a directly enclosing class or enum declaration (§8.5.1).

接口(interface)字段是公共(public)的,由实现该接口(interface)的类继承。来自 JLS:

A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

如果您想让该字段只能在实现成员接口(interface)的类中访问,您可以将其声明放在封闭的顶级范围内。

class TestingInterfaceClass {
    private static final int i = 0;

    private interface InnerInterface {
        // ...
    }

    class inner implements InnerInterface {
        // ...
    }

关于java - 私有(private)接口(interface)中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011737/

相关文章:

java - 无法从其他 fragment 加载 fragment

Java Switch 和 Or 语句

java - 如何将多边形划分为子多边形并为其分配 id

php - 抽象类无法实现? (PHP 5.2.9)

java - Java类可以实现C++接口(interface)吗

c++ - 在 C++ 中,为什么分组没有被语言强制应用于类/结构的公共(public)、私有(private)和 protected 成员?

安卓 : Play a video from a private application file

c++ - 没有对多个基类中的模板化成员函数进行访问或歧义检查

java - 从 Java 调用 shell 命令不好吗?

c# - 通用接口(interface)编译但在运行时不起作用