定义:
没有引用类型变量指向的对象称为匿名对象(没有名字的对象)
要注意的事项:
1、我们一般不会给匿名对象赋予属性值,因为永远无法获取到。
2、两个匿名对象永远都不可能是同一个对象。
//需求:使用Java类描述一个学生类
class Student{
int num;
String name;
public void studg(){
System.out.println("好好学习");
}
}
class Demo1{
public static void main(String[] args){
//创建一个学生对象
//Student s = new Student(); 不是匿名对象
new Student();//创建了一个对象但是没有引用 是一个匿名对象
//给匿名对象定义属性
new Student().name = "狗蛋";
//访问匿名对象
System.out.println(new Student().name);//输出 null,并不是输出 狗娃
System.out.println();
}
}
class Demo2{
public static void main(String[] args){
//"==" 用于引用类型变量时,比较的是内存地址。判断两个对象是否为同一个对象
System.out.println(new Student()== new Student());
//false,因为每 new 一次就会产生一个新的对象
System.out.println();
}
}
匿名对象的好处:
1、简化书写
2、执行完被垃圾回收机制释放
应用场景:
1、如果一个对象需要调用一个方法,而调用完这个方法之后,该对象就不再使用了,这时候可以使用匿名对象
2、可以作为实参调用一个函数。
//需求:调用Student 的 study 方法
class Demo{
public static void main(String[] args){
new student().study();
}
}