1:匿名內(nèi)部類,匿名內(nèi)部類也就是沒有名字的內(nèi)部類。
2:匿名內(nèi)部類的作用
正因為沒有名字,所以匿名內(nèi)部類只能使用一次,它通常用來簡化代碼編寫。
3:匿名內(nèi)部類的實現(xiàn)
匿名內(nèi)部類的兩種實現(xiàn)方式:第一種,繼承一個類,重寫其方法;第二種,實現(xiàn)一個接口(可以是多個),實現(xiàn)其方法。
4:匿名內(nèi)部類的創(chuàng)建
匿名類是不能有名稱的類,所以沒辦法引用它們。必須在創(chuàng)建時,作為new語句的一部分來聲明它們。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.mianshi.test; /** * 類名稱:AnonymousInnerClassTest * 描述: 匿名內(nèi)部類測試 * 創(chuàng)建人:王秋林 * 創(chuàng)建時間:2017-2-12 */ public class AnonymousInnerClassTest { public static void main(String args[]){ AnonymousInnerClassTest test = new AnonymousInnerClassTest(); test.show(); } //在這個方法中構(gòu)造了一個匿名內(nèi)部類 private void show(){ Out anonyInter = new Out(){ //獲取匿名內(nèi)部類實例 void show(){ //重寫父類的方法 System.out.println( "this is Anonymous InnerClass showing." ); } }; anonyInter.show(); //調(diào)用其方法 } } //這是一個已經(jīng)存在的類,匿名內(nèi)部類通過重寫其方法,將會獲得另外的實現(xiàn) class Out{ void show(){ System.out.println( "this is Out showing." ); } } |
5:匿名內(nèi)部類的基本實現(xiàn)
(1)抽象方法實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
abstract class Person { public abstract void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println( "eat something" ); } }; p.eat(); } } |
運行結(jié)果:eat something
(2)接口實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
interface Person { public void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println( "eat something" ); } }; p.eat(); } } |
運行結(jié)果:eat something
由上面的例子可以看出,只要一個類是抽象的或是一個接口,那么其子類中的方法都可以使用匿名內(nèi)部類來實現(xiàn)。最常用的情況就是在多線程的實現(xiàn)上,因為要實現(xiàn)多線程必須繼承Thread類或是繼承Runnable接口。
(3)Thread類的匿名內(nèi)部類實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Demo { public static void main(String[] args) { Thread t = new Thread() { public void run() { for ( int i = 1 ; i <= 5 ; i++) { System.out.print(i + " " ); } } }; t.start(); } } |
運行結(jié)果:1 2 3 4 5
(4)Runnable接口的匿名內(nèi)部類實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Demo { public static void main(String[] args) { Runnable r = new Runnable() { public void run() { for ( int i = 1 ; i <= 5 ; i++) { System.out.print(i + " " ); } } }; Thread t = new Thread(r); t.start(); } } |
運行結(jié)果:1 2 3 4 5
二、匿名內(nèi)部類的注意事項
(1)匿名內(nèi)部類不能有構(gòu)造方法。
(2)匿名內(nèi)部類不能定義任何靜態(tài)成員、方法和類。
(3)匿名內(nèi)部類不能是public,protected,private,static。
(4)只能創(chuàng)建匿名內(nèi)部類的一個實例。
(5)一個匿名內(nèi)部類一定是在new的后面,用其隱含實現(xiàn)一個接口或?qū)崿F(xiàn)一個類。
(6)因匿名內(nèi)部類為局部內(nèi)部類,所以局部內(nèi)部類的所有限制都對其生效。
(7)匿名類和內(nèi)部類中的中的this:有時候,我們會用到一些內(nèi)部類和匿名類。當在匿名類中用this時,這個this則指的是匿名類或內(nèi)部類本身。這時如果我們要使用外部類的方法和變量的話,則應(yīng)該加上外部類的類名。
以上就是本篇文章內(nèi)容,需要的朋友可以參考
原文鏈接:http://www.2cto.com/kf/201702/598086.html