匿名对象和垃圾对象
匿名对象
概念: 没有名字的对象,本质还是一个对象
匿名对象的特点:
1.既然是对象,同样可以访问成员
2.匿名对象只能够使用一次,如果需要使用多次,必须使用变量接收
3.匿名对象一旦使用一次完毕,立刻成为垃圾对象,等待垃圾回收期在空闲的时候回收,节约内存资源
4.匿名对象在Java里一般用于访问一次的情况,简化代码,在Android里节约内存资源
代码实现如下
public class OOPDemo04 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Student s1 = new Student();
// new Student();
//
// System.out.println(new Student().name);
//
// new Student().print99MulTable();
new Student().name = "隔壁老王";
System.out.println(new Student().name); // null
String line = new Scanner(System.in).next();
System.out.println(line);
new Test().method(new Student());
}
}
class Test {
public void method(Student s) {
System.out.println(s.name);
}
}
匿名对象内存图
垃圾对象
没有地址引用的对象称为垃圾对象
什么情况下会成为垃圾对象?
1.当指向某个堆区的空间的对象被赋值为null
2.匿名对象第一次使用完毕
3.对象所在的方法调用完毕
4.对象被重新赋值新的地址
代码实现如下
public class OOPDemo05 {
public static void main(String[] args) {
Student s1 = new Student();
// 1.当指向某个堆区的空间的对象被赋值为null
// s1 = null;
// 2.匿名对象第一次使用完毕
new Student().sleep();
// 3.对象所在的方法调用完毕
Demo d = new Demo();
d.method();
// 4.对象被重新赋值新的地址
s1 = new Student();
}
}
class Demo {
public void method() {
Student s = new Student();
}
}