匿名对象的概述
什么是匿名对象
:就是指"没有名字"的对象。
有名字的对象:
Student stu = new Student();
stu.study();
匿名对象:
new Student();
new Student().study();
使用匿名对象
-
特点:匿名对象
只能使用一次
-
使用场景:方法的
参数
,方法的返回值
public class Test { public static void main(String[] args) { // 创建对象 Student stu1 = new Student("张三",18);// 有名字的对象 stu1.show(); //匿名对象 new Student("张三",18).show();// 没有名字的对象 System.out.println("=================================="); // 调用method1方法 Student stu2 = new Student("李四",18);// 0x11901 method1(stu2);// 有名字的对象传参 // 匿名对象的方式传参数 method1(new Student("李四",18)); System.out.println("=================================="); Student stu3 = method2();// 0x11908 stu3.show();// 王五,18 } // 匿名对象的方式传参数的方法 public static void method1(Student stu){// 0x11901 stu.show(); } //返回匿名对象的方法 public static Student method2(){ //Student stu = new Student("王五",18);// 0x11908 //return stu;// 0x11908 return new Student("王五",18); } }
小结
- 匿名对象:就是指"没有名字"的对象。
- 特点:
只能使用一次
- 一定要注意
使用场景