Java 嵌套的默认接口与嵌套的受保护接口有何不同?
Java中嵌套的默认接口和嵌套的受保护接口之间有什么区别?为什么甚至允许嵌套的受保护接口 Test.javaJava 嵌套的默认接口与嵌套的受保护接口有何不同?,java,interface,Java,Interface,Java中嵌套的默认接口和嵌套的受保护接口之间有什么区别?为什么甚至允许嵌套的受保护接口 Test.java public class Test { // not implementable outside of current package interface NestedDefaultInterface { } // not implementable outside of current package? protected interface
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() {
// };
}
}
这里的混乱是关于可见性的
扩展类时,您将从此
引用访问所有受保护的
父属性
对于default
access修饰符,它不会在包外工作
嵌套接口最流行的真实示例是java.util.Map
的Map.Entry
Map
的每个实现都提供自己的条目
实现。(HashMap
中的Node
,TreeMap中的Entry
等)添加了一个示例,您可以在其中找到嵌套接口的用法