为什么可以将内部(又名非静态嵌套)类定义到接口(interface)中?
这有什么意义吗?它们不能存在于包含接口(interface)的实例中,因为接口(interface)不能被实例化,所以...
以下编译:
interface MyInterface
{
static class StaticNestedClass
{
static int a()
{
return 0;
}
int b()
{
return 1;
}
}
class InnerClass
{
static int a()
{
return 0;
}
int b()
{
return 1;
}
}
}
以上两个类之间有什么区别吗? static
是否真的被考虑在内?
请注意,如果您将 interface
更改为 class
,您显然会在 InnerClass
' static int a()
上遇到编译错误>.
此外,请查看以下内容:
interface MyInterface
{
int c=0;
static class StaticNestedClass
{
static int a()
{
return c;
}
int b()
{
return c+1;
}
}
class InnerClass
{
static int a()
{
return c;
}
int b()
{
return c+1;
}
}
}
与外部 包含实体 是一个类时不同,这里当然不存在“内部(非静态嵌套)类可以访问外部字段而静态嵌套类不能”这样的事情t",因为,考虑到我们的外部事物是一个接口(interface),我们的 c
整数是隐式静态的... interface
的嵌套类也是隐式静态的吗?
再一次,StaticNestedClass
和 InnerClass
是一样的吗?
最佳答案
class InnerClass
隐式(由编译器根据 JLS, Section 9.5 转换为)
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
static class InnerClass
因为它在一个界面中。
将接口(interface)更改为类时会出错,因为不允许使用非静态内部类,并且在类的情况下不会隐式转换为静态。
直接回答你的最后一个问题,
是的,StaticNestedClass
和 InnerClass
是一样的
关于java - 嵌套在接口(interface)中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19432720/