这两种实例化类的新对象的方法有什么区别,如下所示:
Test t1=new Test();
Test t2=new Test(){ };
Run Code Online (Sandbox Code Playgroud)
当我尝试下面的代码时,我可以看到两个对象都可以访问该方法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);
}
}
Run Code Online (Sandbox Code Playgroud)