spr*_*ran 8 java interface anonymous-class
请检查下面的Java代码:
public class Test
{
public static void main(String arg[]) throws Throwable
{
Test t = new Test();
System.out.println(t.meth().s); //OP: Old value
System.out.println(t.meth().getVal()); //OP: String Implementation
}
private TestInter meth()
{
return new TestInter()
{
public String s = "String Implementation";
public String getVal()
{
return this.s;
}
};
}
}
interface TestInter
{
String s = "Old value";
String getVal();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我已匿名创建了一个界面.当我直接访问界面变量时,它将显示"旧值".
t.meth().s =>"旧价值"
通过getVal()方法访问它会返回正确的值,
t.meth().getVal()=>"字符串实现"
我不明白这段代码是如何工作的,有人可以向我解释一下吗?
该s接口中声明的变量是完全独立的从s你已经在你的匿名内部类声明的变量.
接口变量实际上只是设计为常量 - 它们不是每个实现需要提供的API的一部分.特别是,它们是隐含的静态和最终的.
从JLS第9.3节:
接口主体中的每个字段声明都是隐式的public,static和final.允许为这些字段冗余地指定任何或所有这些修饰符.
您通过实现实例访问该字段的事实是无关紧要的 - 此代码:
System.out.println(t.meth().s);
Run Code Online (Sandbox Code Playgroud)
有效地:
t.meth();
System.out.println(TestInter.s);
Run Code Online (Sandbox Code Playgroud)
我强烈建议你避免在接口中使用变量,除了真正的常量......即便如此,只有在它真正有意义的地方.目前还不清楚你想要实现什么,但在界面中声明一个字段并不是IMO的好方法.