一,内部类访问成员
- 1,内部类可以直接访问外部类的成员,包括私有。
- 2,外部类要访问内部类,必须建立内部类对象。
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
|
class Outer { int x = 3 ; class Inner{ void function(){ System.out.println( "inner : " + x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { Outer out = new Outer(); out.method(); } } |
二,访问内部类成员
1,直接访问内部类的中的成员
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 = 3 ; class Inner{ void function(){ System.out.println( "inner : " + x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { //Outer out = new Outer(); //out.method(); Outer.Inner in = new Outer(). new Inner(); in.function(); } } |
2,访问成员
之所以可以直接访问外部类的成员,是因为内部类中持有了一个外部类的引用,格式: 外部类名.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
26
27
28
29
30
31
32
33
34
|
class Outer { int x = 3 ; class Inner{ int x = 4 ; void function(){ int x = 6 ; System.out.println( "inner : " + x); System.out.println( "inner : " + this .x); System.out.println( "inner : " + Outer. this .x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { //Outer out = new Outer(); //out.method(); Outer.Inner in = new Outer(). new Inner(); in.function(); } } |
到此这篇关于Java十分钟精通内部类的使用的文章就介绍到这了,更多相关Java 内部类内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.51cto.com/u_15283585/5154338