Java内部类和静态嵌套类 [英] Java inner class and static nested class

查看:27
本文介绍了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?

推荐答案

来自 Java 教程:

嵌套类分为两类:静态和非静态.声明为静态的嵌套类简称为静态嵌套类.非静态嵌套类称为内部类.

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

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

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 outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

请参阅:Java 教程 - 嵌套类

为了完整起见,还有一个内部类没有封闭实例:

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; } };
}

这里,new A() { ... } 是一个在静态上下文中定义的内部类,没有封闭的实例.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆