一:內(nèi)部類可直接訪問外部類的成員變量,包括外部類私有的成員變量
二:外部類要訪問內(nèi)部類的成員變量,需要建立內(nèi)部類的對象
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
|
class Outer{ int x= 110 ; public void show(){ System.out.println( "外部類的x=" +x); } public void showInner(){ Inner inner= new Inner(); inner.show(); System.out.println(inner.x); } class Inner{ //內(nèi)部類 int x= 220 ; public void show(){ System.out.println( "內(nèi)部類的x=" +x); } } } public class OuterDemo { public static void main(String[] args) { Outer outer= new Outer(); outer.show(); outer.showInner(); Outer.Inner outerInner= new Outer(). new Inner(); //特殊情況.外部類直接訪問內(nèi)部類成員變量 outerInner.show(); } } |
內(nèi)部類之所以可以直接訪問外部類的成員變量,是因為內(nèi)部類持有外部類的引用。格式:外部類名.this
如:System.out.println("x="+Outer.this.x);//訪問外部類的x
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
|
class Outer{ int x= 110 ; class Inner{ int x= 220 ; public void show(){ int x= 330 ; System.out.println( "x=" +x); //訪問show()中的x System.out.println( "x=" + this .x); //訪問內(nèi)部類的x System.out.println( "x=" +Outer. this .x); //訪問外部類的x } } void showInner(){ Inner inner= new Inner(); inner.show(); } } public class OuterDemo { public static void main(String[] args) { Outer outer= new Outer(); outer.showInner(); } } |
在內(nèi)部類(一)和內(nèi)部類(二)中,內(nèi)部類都是作為全局變量出現(xiàn)的即定義在了類里 ,在此獎內(nèi)部類定義為局部變量,即定義在方法里.尤其注意:此時內(nèi)部類要想訪問局部變量,那么此 局部變量必須是被final修飾的,如此處的y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package cn.com; class Outer { int x = 110 ; public void show() { final int y= 99 ; class Inner { // 內(nèi)部類 int x = 880 ; public void showInner() { System.out.println( "局部變量y=" + y); } } new Inner().showInner(); } } public class OuterDemo { public static void main(String[] args) { Outer outer = new Outer(); outer.show(); } } |
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/lfdfhl/article/details/8195036