Non-static Nested Class or Static Nested Class

来源:互联网 发布:ant安装 linux 编辑:程序博客网 时间:2024/06/09 23:28

内部类

  1. 内部类是一个独立的实体,跟类中的方法不同,它不能被子类重写,自己也可以继承(extends)和实现(implements)
  2. 外部类的引用:OuterClass.this,例如Employee.this
  3. 内部类对象的创建:OuterObject.new InnerClass(),例如:

    Employee e = new Employee();Inner in = e.new Inner();
  4. 内部类在编译阶段编译器会将其变成普通的类。在虚拟机中没有内部类的存在,在编译后,内部类对外部类的的访问权限需要借助Bridge Method(桥接方法)、一个Outer-class Reference(外部类引用)和一个带参数的构造器用于对Outer-class Reference初始化)。编译器会自动生成Bridge Method、Outer-class Reference和带参构造器。例子中生成了Employee.class和Employee$Inner.class两个文件,用javap反编译命令可以获得如下类信息:
// before compileclass Employee{    private String name;    public class Inner{        public void print(){            System.out.println("I'm inner class");        }    }}// Employee$Inner.class Compiled from "Employee.java"class Employee$Inner {  final Employee this$0;                           //Outer-class Reference  private Employee$Inner(Employee);  public void print();  static java.lang.String access$000(Employee);    // Bridge Method}// Employee.class Compiled from "Employee.java"public class Employee extends java.util.HashSet {  private java.lang.String name;}

匿名内部类

  1. 匿名内部类一定继承(或者实现)一个类(或者接口)。
  2. 匿名内部类没有构造器。初始化在初始化块中。
  3. 匿名内部类使用的外部变量时,不能更改外部变量的值。
 int i = 5; MyOuter out = new MyOuter() {     public void chanegeI() {        // [error]        // Variable 'i' accessed from within inner class,         // need to be final or effectively final.        i = 5;     } };

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

  1. n-snc(Non-Static nested Class,非静态内部类)拥有访问外部类全部资源的能力;snc只能够访问外部类的静态资源。
  2. n-snc(Static nested Class,静态内部类)不能在含有内部类,即不能进行n-snc嵌套;snc可以嵌套。

Why Use Nested Classes?

  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such “helper classes” makes their package more streamlined.

  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

为什么要使用内部类?

  1. 逻辑上分析,类A只被类B所使用,任何其他类跟类A都没有关系,这时候把A变成B的内部类。
  2. 增强封装性:如果想让类A能够看到类B的资源,类B又不需要知道A的存在,这时候使用内部类。
  3. 从它的能力上分析:
    • 因为内部类和外部类是相互独立的,因此可以同时实现同一个接口,并对其中的方法进行不同的实现。
    • 可以实现多继承。
    • 如果有这样的需求:同一签名的方法在一个类中有不同的实现,可以使用内部类。

为什么使用静态内部类而不是用内部类?

  1. 安全:需要给内部类对象一个有力的限制,限制它只能访问外部类的静态资源,不能访问其他资源时,使用静态内部类。
  2. 嵌套:是有时候根据需求,需要内部类之间的嵌套,因此需要设置为静态内部类。
0 0
原创粉丝点击