Java | 静态嵌套类(Static Nested Class)
前言
定义
静态嵌套类(Static Nested Class),是 Java 中对类的一种定义方式,是嵌套类的一个分类。
Java 编程语言允许一个类被定义在另一个类中,这样的类就称为嵌套类。嵌套类分为两种:静态的和非静态的。用 static
关键字来声明的嵌套类,就称为静态嵌套类。
包含嵌套类的类,可称为外围类(Enclosing Class)或外部类(Outer Class)。静态嵌套类不能访问其外围类的其他成员。静态嵌套类作为其外部类的成员,它可声明为 private
、public
、protected
或包私有的。
- 提示:外部类只能声明为
public
或包私有的。
概述
与类的方法和变量一样,静态嵌套类与其外部类相关联。与类的静态方法一样,静态嵌套类不能直接引用其外围类中定义的实例变量或方法。
- 1 /**
- 2 * 定义一个公共的 OuterClass 类。
- 3 */
- 4 public class OuterClass {
- 5 private final String name;
- 6
- 7 public static void main(String[] args) {
- 8 String name = "Java";
- 9 OuterClass outerObject = new OuterClass(name);
- 10 OuterClass.StaticNestedClass nestedObject =
- 11 new OuterClass.StaticNestedClass(name);
- 12 System.out.println(outerObject.getName());
- 13 System.out.println(nestedObject.getName());
- 14 }
- 15
- 16 /**
- 17 * 定义一个 OuterClass 类的构造方法。
- 18 *
- 19 * @param name 表示一个名称字符串。
- 20 */
- 21 public OuterClass(String name) {
- 22 this.name = name;
- 23 }
- 24
- 25 public String getName() {
- 26 return name;
- 27 }
- 28
- 29 /**
- 30 * 定义一个包私有的 StaticNestedClass 类。
- 31 */
- 32 static class StaticNestedClass {
- 33 private final String name;
- 34
- 35 /**
- 36 * 定义一个 StaticNestedClass 类的构造方法。
- 37 *
- 38 * @param name 表示一个名称字符串。
- 39 */
- 40 public StaticNestedClass(String name) {
- 41 this.name = name + " (in the nested object)";
- 42 }
- 43
- 44 public String getName() {
- 45 return name;
- 46 }
- 47 }
- 48 }
- 49 /* 输出结果:
- 50 Java
- 51 Java (in the nested object)
- 52
- 53 */
在上述示例中,若 StaticNestedClass 类的实例在创建时需要使用 OuterClass 类的成员变量,则可向其构造方法传递该变量的值。
- 提示:静态嵌套类在与其外部类或其他类的实例成员进行交互的时候,就像任何其他顶层类(Top-Level Class)一样。实际上,静态嵌套类在行为上就是一个顶层类,为了便于打包,它被嵌套在了另一个顶层类中。
请用外围类名来访问静态嵌套类,例如,在为静态嵌套类创建对象时,请使用以下语法:
- 1 OuterClass.StaticNestedClass nestedObject =
- 2 new OuterClass.StaticNestedClass(name);