1+ /*
2+ * Session1: 以下是一个测试类,用于在控制台显示某些信息
3+ */
4+ class Test {
5+ public static void main (String [] args ) {
6+ new Outer ().show ();
7+ System .out .println ("---------------分界线【1】---------------" );
8+ new Outer ().new InnerA ().show ();
9+ System .out .println ("---------------分界线【2】---------------" );
10+ new Outer .InnerB ().show ();
11+ System .out .println ("---------------分界线【3】---------------" );
12+ //匿名内部类
13+ new Inter () {
14+ int num = 4 ;
15+ @ Override
16+ public void show () {
17+ System .out .println ("num=" + num );
18+ System .out .println ("(5) 调用了匿名类中方法show()" );
19+ }
20+ }.show ();
21+ System .out .println ("---------------分界线【4】---------------" );
22+ //匿名内部类。并未重写方法
23+ new Inter () {
24+ // 这里没有重写方法,会调用接口中的默认方法
25+ }.show ();
26+ System .out .println ("---------------分界线【5】---------------" );
27+ }
28+ }
29+
30+ /*
31+ * Session2: 以下定义了一个接口。
32+ * 注意:java8 之后,接口中的方法允许在接口的定义时实现。这与我们的教材是有差异的
33+ */
34+ interface Inter {
35+ int num = 1 ; //常量int 前面省略了:static final
36+ default void show () {
37+ System .out .println ("num=" + num );
38+ System .out .println ("(1) 调用了接口Inter 中方法show()" );
39+ }
40+ }
41+
42+ /*
43+ * Session3: 以下定义了一个普通的类Outer。Outer 是一个外部类
44+ */
45+ class Outer {
46+ private int num = 2 ; //part1: 类Outer 的成员变量
47+
48+ //part2: 类Outer 的成员内部类InnerA
49+ class InnerA {
50+ public void show () {
51+ System .out .println ("num=" + num );
52+ System .out .println ("(2) 调用了【成员内部类】InnerA 中的方法show()" );
53+ }
54+ }
55+
56+ //part3: 类Outer 的成员内部类InnerB,并且它是一个静态内部类
57+ static class InnerB implements Inter {
58+ //下面的代码重写了接口Inter 中的方法show()
59+ public void show () {
60+ System .out .println ("num=" + num );
61+ System .out .println ("(3) 调用了【静态成员类】InnerB 中的方法show()" );
62+ }
63+ }
64+
65+ //part4: 以下是Outer 类的一个成员方法show()(或者叫普通方法)
66+ public void show () {
67+ int num = 3 ; //part4-1: 定义局部变量
68+
69+ //part4-2:内部类InnerC 定义在方法show()中,因此它是一个局部的内部类
70+ class InnerC implements Inter {
71+ // 下面的代码重写了接口Inter 中的方法show()
72+ public void show () {
73+ System .out .println ("num=" + num );
74+ System .out .println ("(4) 调用了【局部内部类】InnerC 中的方法show()" );
75+ }
76+ }
77+
78+ new InnerC ().show (); //在这里调用了内部类某个实例的show()方法
79+ }
80+ }
0 commit comments