java - 嵌套默认接口(interface)与嵌套 protected 接口(interface)有何不同?

标签 java interface

Java 中嵌套默认接口(interface)和嵌套 protected 接口(interface)有什么区别?为什么甚至允许嵌套 protected 接口(interface)?

测试.java

public class Test {
    // not implementable outside of current package
    interface NestedDefaultInterface {

    }

    // not implementable outside of current package?
    protected interface NestedProtectedIface {

    }
}

// both interfaces can be implemented
class Best implements Test.NestedProtectedIface, Test.NestedDefaultInterface { 

}

MyClass.java

class AClass implements Test.NestedProtectedIface { //Error

}

class AnotherClass implements Test.NestedDefaultInterface { //Error

}

class OneMoreClass extends Test implements Test.NestedProtectedIface { //Error

}

最佳答案

显示视觉差异:

package com.one

public class Test {
    // not implementable outside of current package
    interface NestedDefaultInterface {

    }

    // implementable in child classes outside of package
    protected interface NestedProtectedIface {

    }
}

包装外:

package com.two

class SubTest extends Test { 
    public void testProtected() {
        NestedProtectedIface npi = new NestedProtectedIface () {
           // implementation
        };
    }

    public void testDefault() {
        // Won't compile!
    //    NestedDefaultInterface ndi = new NestedDefaultInterface() {
    //    };
    }
}

这里的困惑在于可见性。

当你扩展一个类时,你将可以访问所有 protected来自 this 的父属性引用。

对于default访问修饰符在包之外不起作用。

现实世界中最流行的嵌套界面示例是 Map.Entry<K,V>java.util.Map

Map的每次实现提供自己的Entry<K,V>执行。 (Node<K,V>HashMapEntry<K,V>TreeMap 等)

关于java - 嵌套默认接口(interface)与嵌套 protected 接口(interface)有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821952/

相关文章:

c# - 在 C# 中使用泛型创建数学库

java - 让线程 hibernate 不同的时间

java - 参数未在 POST 方法 REST Java 中传递

java - Java 中的邮寄地址?

java - 如何更改 Java 中按钮的外观

C#:接口(interface)中的枚举

TypeScript 接口(interface)模板

java - GWT 对 Java 布局管理器有多少支持?

java - IndexOutOfBoundsException : Index: 3, 大小:3

xcode - Xcode场景扩展坞已隐藏