码迷,mamicode.com
首页 > 其他好文 > 详细

匿名对象

时间:2017-07-19 11:54:48      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:logs   blog   参数   []   new   void   匿名对象   调用   nbsp   

匿名对象:就是没有名字的对象。

匿名对象的应用场景:
A:调用方法,仅仅只调用一次的时候。
注意:调用多次的时候,不适合。
那么,这种匿名调用有什么好处吗?
有,匿名对象调用完毕就是垃圾。可以被垃圾回收器回收。
B:匿名对象可以作为实际参数传递

 1 class Student {
 2     public void show() {
 3         System.out.println("我爱学习");
 4     }
 5 }
 6 
 7 class StudentDemo {
 8     public void method(Student s) {
 9         s.show();
10     }
11 }
12 
13 class NoNameDemo {
14     public static void main(String[] args) {
15         //带名字的调用
16         Student s = new Student();
17         s.show();
18         s.show();
19         System.out.println("--------------");
20         
21         //匿名对象
22         //new Student();
23         //匿名对象调用方法
24         new Student().show();
25         new Student().show(); //这里其实是重新创建了一个新的对象
26         System.out.println("--------------");
27         
28         
29         //匿名对象作为实际参数传递
30         StudentDemo sd = new StudentDemo();
31         //Student ss = new Student();
32         //sd.method(ss); //这里的s是一个实际参数
33         //匿名对象
34         sd.method(new Student());
35         
36         //在来一个
37         new StudentDemo().method(new Student());
38      }
39 }

 

实际参数传递

匿名对象

标签:logs   blog   参数   []   new   void   匿名对象   调用   nbsp   

原文地址:http://www.cnblogs.com/ivevu/p/7204604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!