匿名对象:没有名字的对象
正常的来说,代码是不是应该是这样的
class Demo{
public static void main(String[] args){
Test t=new Test();
t.show();
}
}
class Test{
public void show(){
System.out.println("hello");
}
}
匿名对象实现
class Demo{
public static void main(String[] args){
//匿名对象实现
new Test().show();
}
}
class Test{
public void show(){
System.out.println("hello");
}
}
当然这种方法是有局限性的,当类中的一个方法仅仅需要调用一次时上面的是可以的
class Demo{
public static void main(String[] args){
//当一个类的对象作为实参传递时
test(new Test());
}
public static void test(Test t){
t.show();
t.show1();
}
class Test{
public void show(){
System.out.println("hello");
}
public void show1(){
System.out.println("hi");
}
}
上面这种是当一个类的对象作为实参传递时,使用的匿名对象