Java内部类和静态嵌套类

Java内部类和静态嵌套类

本文介绍了Java内部类和静态嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中内部类和静态嵌套类之间的主要区别是什么?设计/实现是否在选择其中一个中起作用?

What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?

推荐答案

来自:

使用封闭的类名访问静态嵌套类:

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

例如,为静态创建对象嵌套类,使用以下语法:

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

作为内部类实例的对象存在于外部类的实例中。考虑以下类:

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

InnerClass的一个实例只能存在于OuterClass的一个实例,可以直接访问其封闭实例的方法和字段。

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

要实例化内部类,必须首先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

参见:

为了完整性,请注意还有这样的事情:

For completeness note that there is also such a thing as an inner class without an enclosing instance:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}

此处,新A(){... } 是在静态上下文中定义的内部类,并且没有封闭的实例。

Here, new A() { ... } is an inner class defined in a static context and does not have an enclosing instance.

这篇关于Java内部类和静态嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:32