https://www.liaoxuefeng.com/wiki/1252599548343744/1376414781669409

    Java的内部类可分为Inner Class、Anonymous Class和Static Nested Class三种:

    • Inner Class和Anonymous Class本质上是相同的,都必须依附于Outer Class的实例,即隐含地持有Outer.this实例,并拥有Outer Class的private访问权限;
    • Static Nested Class是独立类,但拥有Outer Class的private访问权限。
    1. public class Main {
    2. public static void main(String[] args) {
    3. Outer outer = new Outer("Nested"); // 实例化一个Outer
    4. Outer.Inner inner = outer.new Inner(); // 实例化一个Inner
    5. inner.hello();
    6. }
    7. }
    8. class Outer {
    9. private String name;
    10. Outer(String name) {
    11. this.name = name;
    12. }
    13. class Inner {
    14. void hello() {
    15. System.out.println("Hello, " + Outer.this.name);
    16. }
    17. }
    18. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. Outer.StaticNested sn = new Outer.StaticNested();
    4. sn.hello();
    5. }
    6. }
    7. class Outer {
    8. private static String NAME = "OUTER";
    9. private String name;
    10. Outer(String name) {
    11. this.name = name;
    12. }
    13. static class StaticNested {
    14. void hello() {
    15. System.out.println("Hello, " + Outer.NAME);
    16. }
    17. }
    18. }