相关疑难解决方法(0)

新Test()和新Test(){}之间的区别

这两种实例化类的新对象的方法有什么区别,如下所示:

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)

java anonymous-inner-class

33
推荐指数
4
解决办法
3241
查看次数

标签 统计

anonymous-inner-class ×1

java ×1