Inner Class

  1. public class Main {
  2. public static void main(String[] args) {
  3. Outer outer = new Outer("Nested");
  4. Outer.Inner inner = outer.new Inner();
  5. inner.hello();
  6. }
  7. }
  8. class Outer {
  9. private final 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. }

Anonymous Class匿名

  1. public class Main {
  2. public static void main(String[] args) {
  3. Outer outer = new Outer("Nested");
  4. outer.asyncHello();
  5. }
  6. }
  7. class Outer {
  8. private final String name;
  9. public Outer(String name) {
  10. this.name = name;
  11. }
  12. void asyncHello() {
  13. Runnable r = new Runnable() {
  14. @Override
  15. public void run() {
  16. System.out.println("Hello," + Outer.this.name);
  17. }
  18. };
  19. new Thread(r).start();
  20. }
  21. }

静态内部类

  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 final String NAME = "OUTER";
  9. private final String name;
  10. public 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. }