匿名对象的概述
什么是匿名对象:就是指"没有名字"的对象。
有名字的对象:
Student stu = new Student();
stu.show();
stu.study();
匿名对象:
new Student();
特点:匿名对象只能使用一次
public class Test {
public static void main(String[] args) {
/*
- 匿名对象的概述: 指的就是没有名字的对象
- 匿名对象的特点: 只能使用一次
- 使用场景: 当某个类的对象只需要使用一次的时候,就可以使用匿名对象
例如: 作为方法的参数,或者作为方法的返回值
*/
// 有名字的对象:
Student stu = new Student("张三", 18);
stu.show();
stu.show();
// 一个对象调用了2次show方法
// 匿名对象:
new Student("张三", 18).show();
new Student("张三", 18).show();
// 两个对象分别调用了一次show方法
System.out.println("========================");
// 使用场景一: 作为方法的参数
Student stu1 = new Student();
method1(stu1);
method1(new Student());
}
public static void method1(Student stu) {
System.out.println("执行了");
}
// 使用场景二: 作为方法的返回值
public static Student method2(){
//Student stu1 = new Student();
//return stu1;
return new Student();// 返回的就是Student对象的地址值
}
}
小结
- 匿名对象:就是指"没有名字"的对象。
- 特点: 只能使用一次