参考自:https://blog.csdn.net/qq_24753293/article/details/89105273
基本介绍
- 使用目的:节省内存
- 使用时间:创建对象时
- 使用方法:new 对象名().方法名();
- 使用原理:在创建对象的时候,new在堆内存开辟新空间之后,没有把堆内存中的地址返回给内存的变量进行储存。
- 注意事项:诸事皆宜
代码示例
//有名字的对象
Student s = new Student();
//匿名对象:
new Student();
图形示例
在内存中的过程 上为匿名对象 下为正常
代码总结
class Introduce{
public void Say(){
System.out.println("Hello");
}
public void Bye(){
System.out.println("Bye");
}
}
public class Demo1 {
public static void main(String[] args) {
Introduce introduce = new Introduce(); //常规创建对象
introduce.Say();//栈区地址相同 使用相同对象
introduce.Bye();
new Introduce().Say();//创建对象1
new Introduce().Bye();//创建对象2
}
}