Java - Nested Classes

(本文参考:http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Nested Classes

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

定义

nested classes (嵌套类)分为两种:non-staticstatic,前者通常称作inner classes,后者称作static nested classes

作用域与访问范围

两种nested classes都是其enclosing class的内部成员,non-static classes可以引用到包装类的private成员,static classes没有这个能力。两种nested classes都可以被声明为public/protected/private/package private

作用场景(因原文概括性高,直接引用)

  • It is a way of logically grouping classes that only used in one place.
  • It increases encapsulation.
  • It can lead to more readable and maintainable code.

Static Nested Classes

  • static nested classes不可直接调用其外部类的方法/成员,必须通过一个外部类的实例才能访问(在这一点上,static inner class表现的如同一个top-level class
  • 用如下方式创建一个static nested class实例

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

Inner Classes

  • As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object‘s methods and fields.
  • Cause an inner class is associated with an instance, it cannot define any static members itself.
  • 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.
  • 用如下方式创建一个inner class实例

    OuterClass.InnerClass innerObject = outerObject.new InnerClass();
  • 有两种特殊的inner classes:local classesanonymous class

Shadowing(不知确切的中文翻译是什么,“遮蔽”?)

原文用一段很简洁的代码讲清了这个问题

public class Main {
    public static void main(String[] args) throws Exception {
        (new OuterClass()).new InnerClass().printX(2);
        System.out.println("FINISH!");
    }
}

class OuterClass {
    int x = 0;
    class InnerClass {
        int x = 1;
        public void printX (int x) {
            System.out.println("x=" + x);
            System.out.println("this.x=" + this.x);
            System.out.println("OuterClass.this.x=" + OuterClass.this.x);
        }
    }
}

输出:

x=2
this.x=1
OuterClass.this.x=0
FINISH!

Serialization

  • Serialization of inner classes, including local and annonymous classes, is strongly discouraged.
  • 原因是编译器在compile certain constructs时,会产生synthetic constructs:these are classes, methods, fields, and other constructs that do not have a corresponding construct in the source code.
  • You may have compatibility issues if you serialize an inner class and then deserialize it with a different JRE implementation.
时间: 2024-10-15 21:19:01

Java - Nested Classes的相关文章

Java中的Nested Classes和Inner Classes

Java中的Nested Classes和Inner Classes Java有嵌套类(Nested Classes)和内部类(Inner Classes)的概念. 嵌套类(Nested Classes)分为两种:static and non-static,即静态的和非静态的,静态的嵌套类我们称之静态嵌套类(static nested classes),非静态的嵌套类我们称之为内部类(inner classes). 静态的嵌套类我们可以这样表示: OuterClass.StaticNestedC

Java Nested Class

Normal class(Non-nested class) can only be public, abstract or final. For nested classes, static is allowed. Nested classes(private, public, protected) -> 2 Categories. 1. Static Nested Class (Very Different from C# static class) alpha: Have access t

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them

Top 15 Java Utility Classes

In Java, a utility class is a class that defines a set of methods that perform common functions. This post shows the most frequently used Java utility classes and their most commonly used methods. Both the class list and their method list are ordered

When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions

As mentioned in the section  Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code. Local classes, anonymous classes, an

java 错误 classes路径配置错误

1. 错误显示页 2. 解决步骤 2.1. 查看 root cause 信息 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'urlMapping' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Initialization of bean failed; nested excepti

Replacing the deprecated Java JPEG classes for Java 7

[src: https://blog.idrsolutions.com/2012/05/replacing-the-deprecated-java-jpeg-classes-for-java-7/] In the early days of Java, Sun produced a really handy set of classes to handle JPEG images. These included some really nifty little features like the

Java Date Classes

The main change in the Java 8 date time API is that date and time is now no longer represented by a single number of milliseconds since Jan. 1st 1970, but by the number of seconds and nanoseconds since Jan. 1st 1970. The number of seconds can be both

Java的线程和多线程教程

Java线程(Java Thread)是执行某些任务的一种轻量级进程.Java中的Thread类提供了多线程(multi-threading)功能,应用程序能够创建多个线程并同一时候执行. 在一个应用程序中,一般会有两种类型的线程-用户线程(user thread)和守护线程(daemon thread).当我们启动引用程序时,首先创建用户线程main,我们能够创建多个用户线程和守护线程.当全部的用户线程都运行完成时,JVM就会终止程序. 对不同的线程,我们能够设置对应的优先级,但并不意味着高优