Nested Classes in Java – Java中的嵌套类

最后修改: 2017年 12月 2日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

This tutorial is a quick and to-the-point introduction to nested classes in the Java language.

本教程对Java语言中的嵌套类进行了快速而到位的介绍。

Simply put, Java allows us to define classes inside other classes. Nested classes enable us to logically group classes that are only used in one place, write more readable and maintainable code and increase encapsulation.

简单地说,Java允许我们在其他类中定义类。嵌套类使我们能够对只在一个地方使用的类进行逻辑分组,编写更可读和可维护的代码,并增加封装。

Before we get started, let’s have a look at the several types of nested classes available in the language:

在我们开始之前,让我们看看语言中可用的几种类型的嵌套类。

  • Static nested classes
  • Non-static nested classes
  • Local classes
  • Anonymous classes

In the next sections, we’re going to discuss each of these in detail.

在接下来的章节中,我们将详细讨论每一个问题。

2. Static Nested Classes

2.静态嵌套类

Here are a few points to remember about static nested classes:

下面是关于静态嵌套类的几个要点,请记住。

  • As with static members, these belong to their enclosing class, and not to an instance of the class
  • They can have all types of access modifiers in their declaration
  • They only have access to static members in the enclosing class
  • They can define both static and non-static members

Let’s see how we can declare a static nested class:

让我们看看如何声明一个静态嵌套类。

public class Enclosing {
    
    private static int x = 1;
    
    public static class StaticNested {

        private void run() {
            // method implementation
        }
    }
    
    @Test
    public void test() {
        Enclosing.StaticNested nested = new Enclosing.StaticNested();
        nested.run();
    }
}

3. Non-Static Nested Classes

3.非静态的嵌套类

Next, here are a few quick points to remember about non-static nested classes:

接下来,这里有几个关于非静态嵌套类的快速记忆点。

  • They are also called inner classes
  • They can have all types of access modifiers in their declaration
  • Just like instance variables and methods, inner classes are associated with an instance of the enclosing class
  • They have access to all members of the enclosing class, regardless of whether they are static or non-static
  • They can only define non-static members

Here’s how we can declare an inner class:

下面是我们如何声明一个内部类。

public class Outer {
    
    public class Inner {
        // ...
    }
}

If we declare a nested class with a modifier static, then it’s a static member one. Otherwise, it’s an inner class. Even though syntactically the difference is just a single keyword (i.e., static), semantically there is a huge difference between these kinds of nested classes. Inner class instances are bound to the enclosing class ones and therefore they have access to their members. We should be aware of this issue when selecting whether to make a nested class be an inner one.

如果我们用修饰语static声明一个嵌套类,那么它就是一个静态成员。否则,它就是一个内部类。尽管语法上的区别只是一个关键词(即static),但从语义上看,这些类型的嵌套类之间有很大的区别。内层类的实例被绑定到外层类的实例上,因此它们可以访问它们的成员。在选择是否让一个嵌套类成为内层类时,我们应该注意到这个问题。

To instantiate an inner class, we must first instantiate its enclosing class.

要实例化一个内层类,我们必须首先实例化其外层类。

Let’s see how we can do that:

让我们看看我们如何能够做到这一点。

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

In the next subsections, we’re going to show some special types of inner classes.

在接下来的几个小节中,我们将展示一些特殊类型的内部类。

3.1. Local Classes

3.1.地方类

Local classes are a special type of inner classes – in which the class is defined inside a method or scope block.

局部类是一种特殊的内部类–其中类被定义在一个方法或范围块中。

Let’s see a few points to remember about this type of class:

让我们看看关于这种类型的班级需要记住的几个要点。

  • They cannot have access modifiers in their declaration
  • They have access to both static and non-static members in the enclosing context
  • They can only define instance members

Here’s a quick example:

这里有一个简单的例子。

public class NewEnclosing {
    
    void run() {
        class Local {

            void run() {
                // method implementation
            }
        }
        Local local = new Local();
        local.run();
    }
    
    @Test
    public void test() {
        NewEnclosing newEnclosing = new NewEnclosing();
        newEnclosing.run();
    }
}

3.2. Anonymous Classes

3.2.匿名类

Anonymous classes can be used to define an implementation of an interface or an abstract class without having to create a reusable implementation.

匿名类可以用来定义一个接口或抽象类的实现,而不需要创建一个可重用的实现。

Let’s list a few points to remember about anonymous classes:

让我们列举一下关于匿名班的几点注意事项。

  • They cannot have access modifiers in their declaration
  • They have access to both static and non-static members in the enclosing context
  • They can only define instance members
  • They’re the only type of nested classes that cannot define constructors or extend/implement other classes or interfaces

To define an anonymous class, let’s first define a simple abstract class:

要定义一个匿名类,首先让我们定义一个简单的抽象类。

abstract class SimpleAbstractClass {
    abstract void run();
}

Now let’s see how we can define an anonymous class:

现在我们来看看如何定义一个匿名类。

public class AnonymousInnerUnitTest {
    
    @Test
    public void whenRunAnonymousClass_thenCorrect() {
        SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
            void run() {
                // method implementation
            }
        };
        simpleAbstractClass.run();
    }
}

For more details, we may find useful our tutorial on Anonymous Classes in Java.

关于更多的细节,我们可能会发现我们的Java中的匿名类教程很有用。

4. Shadowing

4.阴影

The declaration of the members of an inner class shadow those of the enclosing class if they have the same name.

如果一个内层类的成员与外层类的成员有相同的名称,那么内层类的声明将影射外层类的成员

In this case, the this keyword refers to the instances of the nested class and the members of the outer class can be referred to using the name of the outer class.

在这种情况下,this关键字指的是嵌套类的实例,外侧类的成员可以用外侧类的名称来引用。

Let’s see a quick example:

让我们看一个快速的例子。

public class NewOuter {

    int a = 1;
    static int b = 2;

    public class InnerClass {
        int a = 3;
        static final int b = 4;

        public void run() {
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            System.out.println("NewOuterTest.this.a = " + NewOuter.this.a);
            System.out.println("NewOuterTest.b = " + NewOuter.b);
            System.out.println("NewOuterTest.this.b = " + NewOuter.this.b);
        }
    }

    @Test
    public void test() {
        NewOuter outer = new NewOuter();
        NewOuter.InnerClass inner = outer.new InnerClass();
        inner.run();

    }
}

5. Serialization

5.序列化

To avoid a java.io.NotSerializableException while attempting to serialize a nested class, we should:

为了避免在试图序列化一个嵌套类时出现java.io.NotSerializableException,我们应该。

  • Declare the nested class as static
  • Make both the nested class and the enclosing class implement Serializable

6. Conclusion

6.结论

In this article, we’ve seen what nested classes are and their different types. We also took a look at how field visibility and access modifiers differ across those different types.

在这篇文章中,我们已经看到了什么是嵌套类以及它们的不同类型。我们还看了一下字段的可见性和访问修改器在这些不同类型中的不同。

As always, the full implementation of this tutorial can be found over on GitHub.

一如既往,本教程的完整实现可以在GitHub上找到over