What is the difference between these two ways of instantiating new objects of a class as follows:
Test t1=new Test();
Test t2=new Test(){ };
When I tried the following code, I could see that both objects could access the method foo()
, but t2 cannot access the variable x
(variable x
cannot be resolved):
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);
}
}
See Question&Answers more detail:os