匿名对象介绍
匿名对象是没有名字的实体,也就是该实体没有对应的变量名引用。
运行一次,直接就被回收掉了,节省内存空间。
通常我们定义一个对象并调用方法会这样去写:
Car car = new Car();
car.run();
如果们使用匿名对象就可以这样写:
new Car(); // 匿名对象其实就是定义对象的简写格式。
new Car().run();
匿名对象的特征:
1)创建的匿名类的对象只能够调用一次。
2)匿名对象只在堆内存中开辟空间,而不存在栈内存的引用。
3) 每次创建匿名对象都是不同的对象(任何两个匿名对象使用==比较,永远返回false) 。
匿名对象的用途:
1)当对象对方法进行一次调用的时候,可以使用匿名对象对代码进行简化。
为什么只对方法,而不调用属性呢?因为匿名对象调用属性没意义。
如果对象要对成员进行多次调用,必须给对象起个名字,不能再使用匿名对象。
public class Test {
public static void main(String[] args) {
// 匿名对象可以调用属性,但是没有意义,因为调用后就变成垃圾, 如果需要赋值还是用有名字对象
new Car().color = "red";
new Car().num = 4;
new Car().run();
//匿名对象只适合对方法的一次调用,因为调用多次就会产生多个对象,不如用有名字的对象
// new Car().run();
}
}
class Car {
String color; // 颜色
int num; // 轮胎数
public void run() {
System.out.println("coloer: " + color + ", num: " + num);
}
}
执行结果:
coloer: null, num: 0
2)匿名对象可以实际参数进行传递。
public class Test {
public static void main(String[] args) {
printStudentInfo(new Student("爪哇菌", 12345)); // 传递匿名对象
}
public static void printStudentInfo(Student student) {
System.out.println(student.getStuName()+", "+student.getStuId());
}
}
class Student {
private String stuName;
private Integer stuId;
public Student(String stuName, Integer stuId) {
this.stuName = stuName;
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public Integer getStuId() {
return stuId;
}
}
执行结果如下:
爪哇菌, 12345