本文介绍了静态和非静态初始化代码块有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于 static 关键字的一种特殊用法.可以使用 static 关键字来覆盖类中不属于任何函数的代码块.例如下面的代码编译:

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to any function. For example following code compiles:

public class Test {
    private static final int a;
    static {
        a = 5;
        doSomething(a);
    }
    private static int doSomething(int x) {
        return (x+5);
    }
}

如果删除 static 关键字,它会抱怨,因为变量 afinal.但是,可以同时删除 finalstatic 关键字并使其编译.

If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.

这在两个方面都让我感到困惑.我应该如何拥有不属于任何方法的代码部分?怎么可能调用它?一般来说,这种用法的目的是什么?或者更好的是,我在哪里可以找到关于此的文档?

It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?

推荐答案

带有 static 修饰符的代码块表示一个 class 初始化器;如果没有静态修饰符,代码块就是一个 instance 初始化器.

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

类初始化器在类加载时(实际上,当它被解析时,但这是一个技术问题)按照它们定义的顺序执行(自上而下,就像简单的变量初始化器).

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

实例初始化器按照类被实例化时定义的顺序执行,紧接在构造函数代码执行之前,紧接在调用超级构造函数之后.

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

如果您从 int a 中删除 static,它会成为一个实例变量,您无法从静态初始化程序块访问该变量.这将无法编译并出现错误非静态变量 a 无法从静态上下文中引用".

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

如果你也从初始化块中删除了 static,它就会变成一个实例初始化器,所以 int a 在构造时被初始化.

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

这篇关于静态和非静态初始化代码块有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:45