gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:52 24 4
gpt4 key购买 nike

我正在尝试测试 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com