次のように、クラスの新しいオブジェクトをインスタンス化するこれら 2 つの方法の違いは何ですか。
Test t1=new Test();
Test t2=new Test(){ };
次のコードを試してみたところ、両方のオブジェクトが methodfoo()
にアクセスできることがわかりましたが、t2 はvariable x
( variable x
can't be resolve) にアクセスできません。
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);
}
}