嵌套类
Java支持如下几种嵌套类:
- nested class,定义在类型内部的类型。
- static nested class,使用 static 声明的 nested class,static nested class 可以访问所有外部类的静态成员。
- inner class,没有使用 static 声明的 nested class,inner class 可以访问所有外部类的实例成员,inner class 不能定义静态成员。
代码示例
1 public class Program {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7 OuterClass outer = new OuterClass();
8 OuterClass.InnerClass inner = outer.new InnerClass();
9 OuterClass.InnerClass.InnerInnerClass innerInner = inner.new InnerInnerClass();
10 outer.show();
11 inner.show();
12 innerInner.show();
13
14 OuterClass.StaticNestedClass staticNested=new OuterClass.StaticNestedClass();
15 OuterClass.StaticNestedClass.StaticNestedNestedClass staticNestedNested=new OuterClass.StaticNestedClass.StaticNestedNestedClass();
16
17 staticNested.show();
18 staticNestedNested.show();
19 }
20 }
21
22 class OuterClass {
23 int x = 1;
24 static int i = 1;
25
26 void show() {
27 System.out.println(x);
28 System.out.println(i);
29 }
30
31 class InnerClass {
32 int y = 2;
33
34 void show() {
35 System.out.println(x);
36 System.out.println(y);
37 }
38
39 class InnerInnerClass {
40 int z = 3;
41
42 void show() {
43 System.out.println(OuterClass.this.x);
44 System.out.println(y);
45 System.out.println(z);
46 }
47 }
48 }
49
50 static class StaticNestedClass {
51 static int j = 2;
52
53 void show() {
54 System.out.println(i);
55 System.out.println(j);
56 }
57
58 static class StaticNestedNestedClass {
59 static int k = 3;
60
61 void show() {
62 System.out.println(i);
63 System.out.println(j);
64 System.out.println(k);
65 }
66 }
67 }
68 }
特殊的inner class:local class
1 public class LocalClassExample {
2
3 static String staticValue = "static value";
4 String instanceValue = "instance value";
5
6 public void test() {
7
8 final String finalLocalValue = "final local value";
9
10 class LocalClass {
11 void test() {
12 System.out.println(staticValue);
13 System.out.println(instanceValue);
14 System.out.println(finalLocalValue);
15 }
16 }
17
18 LocalClass local = new LocalClass();
19 local.test();
20 }
21 }
除了inner class的规则之外,local class可以访问局部final变量,在Java8中有更多的改进。特殊的local class:anonymous class
1 public class Program {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7 execute(new Action() {
8 @Override
9 public void execute() {
10 System.out.println("执行业务逻辑");
11 }
12 });
13 }
14
15 static void execute(Action action) {
16 System.out.println("事物开始");
17 action.execute();
18 System.out.println("事物结束");
19 }
20 }
21
22 interface Action {
23 void execute();
24 }
尚学堂给同学们带来全新的Java300集课程啦!java零基础小白自学Java必备优质教程_手把手图解学习Java,让学习成为一种享受_哔哩哔哩_bilibili