【发布时间】:2013-10-26 07:08:00
【问题描述】:
为什么可以在接口中定义内部(又名非静态嵌套)类?
这有意义吗?它们不能存在于包含接口的实例中,因为接口不能被实例化,所以...
以下编译:
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",因为鉴于我们的外部事物是一个接口,我们的 c 整数是隐式静态的...interface 的嵌套类也是隐式静态的吗?
再说一遍,StaticNestedClass 和 InnerClass 是一样的吗?
【问题讨论】:
-
我认为
class InnerClass是隐式静态的,类似于c -
@Cruncher 实际上,接口中的任何非方法都会被编译器自动标记为
static。
标签: java interface static nested-class jls