我已经开始准备OCJP7考试了,我发现这一章似乎很复杂。
假设我有这段代码:
class Outer1{
interface InnerInterface{
String x = "test";
}
class InnerClass{
String x = "test";
}
}
class Outer2{
static interface NestedInterface{
String x = "test";
}
static class NestedClass{
String x = "test";
}
}
class Main{
public static void main(String [] args){
String s1 = Outer1.InnerInterface.x;
String s2 = new Outer1().new InnerClass().x;
String s3 = Outer2.NestedInterface.x;
String s4 = new Outer2.NestedClass().x;
}
}
你能告诉我为什么我们可以以相同的方式访问 Outer1.InnerInterface.x
和 Outer2.NestedInterface.x
吗?内部接口(interface)默认是静态的?我正在尝试建立一些联系以使它们更清楚。
最佳答案
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
接口(interface)不能实例化。因此,它们只有作为静态才有意义。将嵌套接口(interface)声明为静态是多余的。
此外,练习使用了令人困惑的接口(interface)名称。
InnerClass
和NestedClass
都是嵌套类。但是只有 InnerClass
是内部类,因为“内部类”意味着“非静态嵌套类”。
类似地,人们可能期望 InnerInterface
是一个“内部接口(interface)”,意思是“非静态嵌套接口(interface)”;但这样的事情并不存在。 InnerInterface
和NestedInterface
都是嵌套接口(interface),都不是内部接口(interface)。
关于Java 内部类和嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710637/