內(nèi)部類的介紹
定義在另外一個類中的類,叫內(nèi)部類
成員內(nèi)部類
1..new 創(chuàng)建成員內(nèi)部類必須先創(chuàng)建外部類的實例,然后通過.new 創(chuàng)建內(nèi)部類的對象
2..this 可以通過外部類的類名.this去訪問外部類的所有屬性和方法。
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
|
public class Test1 { String name = "asnd" ; public static void main(String[] args) { Test1 test1 = new Test1(); Inner mInner = test1. new Inner(); mInner.print(); } void show() { System.out.println( "show" ); } public class Inner { String name = "123" ; private void print(){ show(); System.out.println(name); //打印的是123 System.out.println(Test1. this .name); //打印的是asnd } } } |
匿名內(nèi)部類
沒有名字的類,創(chuàng)建類的同時,也會創(chuàng)建一個對象。
只需要用到一次的類,就可以使用匿名內(nèi)部類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
File file = new File( "D:/cc.txt" ) { @Override public boolean delete() { System.out.println( "是否刪除y/n" ); Scanner input = new Scanner(System.in); String str = input.next(); if (str.equals( "y" )) { return super .delete(); } System.out.println( "刪除失敗" ); return false ; } }; file.delete(); } |
匿名對象
該對象只需要訪問一次.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
new Thread() { @Override public void run() { System.out.println( "線程開始!" ); try { Thread.sleep( 2000 ); System.out.println( "線程結(jié)束!" ); } catch (Exception e) { e.printStackTrace(); } super .run(); } }.start(); |
1.靜態(tài)內(nèi)部類只能訪問外部類靜態(tài)的方法和變量,不能訪問非靜態(tài)。
2.靜態(tài)內(nèi)部類可以不需要創(chuàng)建外部類的引用,而直接創(chuàng)建。
匿名內(nèi)部類訪問局部變量
內(nèi)部類訪問局部變量必須final,如果沒有加,jdk1.8默認加上去了
當(dāng)所使用的變量是在變的時候可以用下面的方法,也可以把下面的i在開始的時候定為靜態(tài)的
1
2
3
4
5
6
7
8
9
|
for ( int i = 0 ; i < 5 ; i++) { final int finali = i; new Thread() { public void run() { System.out.println(finali); }; }.start(); } |
下面介紹一下內(nèi)部類的實現(xiàn)技巧
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
29
30
31
32
|
public static void main(String[] args) { Lam mLam = new Lam(); //第一種實現(xiàn)的方法 mLam.to( new Ligh() { @Override public void shin() { System.out.println( "on的第一種方法" ); } }); //第二種實現(xiàn)方法 class MyLam implements Ligh{ @Override public void shin() { System.out.println( "第二種" ); }} mLam.to( new MyLam()); } } interface Ligh { void shin(); } class Lam { public void to(Ligh ligh) { ligh.shin(); System.out.println( "on" ); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!