匿名對(duì)象:沒有名字的對(duì)象。
非匿名對(duì)象:
ClassName c=new ClassName();
c.run();
匿名對(duì)象:
new ClassName().run();
注意事項(xiàng):
1、當(dāng)對(duì)象對(duì)方法僅進(jìn)行一次調(diào)用的時(shí)候,就可以簡(jiǎn)化成匿名對(duì)象。
2、兩個(gè)匿名對(duì)象不可能是同一個(gè)對(duì)象。
3、一般不給匿名對(duì)象賦予屬性值,因?yàn)橛肋h(yuǎn)無法獲取到。
4、運(yùn)行一次,直接就被回收掉了,節(jié)省內(nèi)存空間。
匿名對(duì)象使用的代碼例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Anony{ int a= 1 ; int b= 2 ; void run(){ System.out.println(a+b); } public static void main(String[] args){ new Anony().a= 10 ; //匿名對(duì)象不能重新賦值,賦值仍然失效 Anony a= new Anony(); a.run(); //通過創(chuàng)建對(duì)象的方式去調(diào)用方法 new Anony().run(); //匿名創(chuàng)建對(duì)象并調(diào)用方法 } } |
運(yùn)行結(jié)果:
3
3
匿名內(nèi)部類:匿名內(nèi)部類也就是沒有名字的內(nèi)部類。
格式:
ClassName object=new ClassName(){
/*代碼塊*/
};
注意事項(xiàng):
1、匿名內(nèi)部類必須繼承一個(gè)父類或?qū)崿F(xiàn)一個(gè)接口。
抽象類代碼例子:(接口同理)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
abstract class AnonyTest{ int a= 1 ; int b= 2 ; public abstract void run(); } public class AnonyInner{ public static void main(String[] args){ AnonyTest a= new AnonyTest(){ //抽象匿名類 public void run() { System.out.println(a+b); } }; a.run(); } } |
如果不使用匿名內(nèi)部類來實(shí)現(xiàn)抽象方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
abstract class AnonyTest{ int a= 1 ; int b= 2 ; public abstract void run(); } class AnonyDemo extends AnonyTest{ public void run() { System.out.println(a+b); } } public class AnonyInner{ public static void main(String[] args) { AnonyTest a= new AnonyDemo(); //上轉(zhuǎn)對(duì)象 a.run(); } } |
運(yùn)行結(jié)果:
3
原文鏈接:https://www.idaobin.com/archives/554.html