【笔记】Java内部类

静态内部类和非静态内部类的区别

A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.Java: Static vs inner class - Stack Overflow
inner_class

local class不能访问一般的局部变量,只能访问被final修饰的局部变量

local class不能被static修饰, 因为static只能修饰成员变量, 不能修饰局部变量.
local class中可以直接访问外部类的所有成员, 包括私有成员, 因为其默认持有外部类的引用.
但不能访问它所在作用域中的一般的局部变量, 只能访问被final修饰的局部变量.
为什么必须是final的呢? - 崔鹏飞的Octopress Blog
Java的局部内部类以及final类型的参数和变量 - JAVA夜无眠 - ITeye博客

示例代码

package com.zhoujin7;

public class Outer {
  private static String outerStaticField = "Outer Static Field";
  private String outerInstanceField = "Outer Instance Field";

  public Outer() {
    System.out.println("Outer Class");
  }

  public static void staticPrint() {
    final String localField = "local Field";
    class Local {
      public Local() {
        System.out.println("Local Class");
        System.out.println(outerStaticField);
        System.out.println(localField);
      }
    }
    new Local();
  }

  public static void main(String[] args) {
    new StaticMember();
    System.out.println();
    new Outer().new NonStaticMember();
    System.out.println();
    new Outer().print();
    System.out.println();
    Outer.staticPrint();
  }

  public void print() {
    // JDK 8 可以不用加上这个final
    final String localField = "local Field";
    class Local {
      public Local() {
        System.out.println("Local Class");
        System.out.println(outerInstanceField);
        System.out.println(outerStaticField);
        System.out.println(localField);
      }
    }
    new Local();
  }

  public static class StaticMember {
    public StaticMember() {
      System.out.println("Static Class");
      System.out.println(outerStaticField);
    }
  }

  public class NonStaticMember {
    public NonStaticMember() {
      System.out.println("Non-Static Member Class");
      System.out.println(outerInstanceField);
    }
  }
}
comments powered by Disqus
备案号: 湘ICP备16015340号