这两种实例化类的新对象的方式有什么区别,如下所示:
Test t1=new Test();
Test t2=new Test(){ };
当我尝试以下代码时,我可以看到两个对象都可以访问方法foo()
,但 t2 无法访问variable x
(variable x
无法解析):
public class Test
{
int x=0;
public void foo(){ }
public static void main (String args[])
{
Test t1=new Test();
Test t2=new Test(){ };
t1.x=10;
t2.x=20;
t1.foo();
t2.foo();
System.out.println(t1.x+" "t2.x);
}
}