lundi 3 mars 2014

Difference between new Test() and new Test() { }


Vote count:

0




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);
}
}


asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire