请检查下面的 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();
}
如您所见,我已经匿名创建了一个界面。当我直接访问接口变量时,它将显示“旧值”。
t.meth().s => "旧值"
通过 getVal() 方法访问它会返回正确的值,
t.meth().getVal() => "字符串实现"
我不明白这段代码是如何工作的,有人能给我解释一下吗?