问题描述
这两种实例化类的新对象的方法有何不同,如下所示:
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(){ };
当我尝试以下代码时,我可以看到两个对象都可以访问方法 foo()
,但是t2无法访问变量x
(变量x
不能待解决):
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);
}
}
推荐答案
测试t2 = new Test();
将创建Test类的对象。
Test t2=new Test();
will create the object of Test class.
但是测试t2 = new Test(){};
将创建一个测试子类的对象(即匿名在这种情况下的内部类)。
But Test t2=new Test(){ };
will create a object of subclass of test (i.e. anonymous inner class in this case).
你可以为那里的任何方法提供实现,如
you can provide implementation for any method over there like
Test t2=new Test(){
public void foo(){ System.out.println("This is foo");}
};
这样当 foo()
方法调用时从对象 t2
它将打印这是foo
。
so that when foo()
method called from object t2
it will print This is foo
.
添加
代码中的编译时错误是由于缺少连接操作符
Compile time error in your code is due to missing concatination operator
System.out.println(t1.x+" "+t2.x);
###
这篇关于新Test()和新Test(){}之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!