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>
中 HashMap
、Entry<K,V>
中 TreeMap
等)
关于java - 嵌套默认接口(interface)与嵌套 protected 接口(interface)有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821952/