静态和非静态初始化代码块之间有什么区别 [英] What is the difference between a static and a non-static initialization code block

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

问题描述

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

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

如果删除静态它抱怨的关键字,因为变量 a final 。但是,可以删除 final static 关键字并进行编译。



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

解决方案

带有静态修饰符的代码块表示初始化程序;如果没有静态修饰符,则代码块是实例初始值设定项。



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



实例初始化程序在实例化时定义的顺序执行,紧接在执行构造函数代码之前,在超级构造函数调用之后立即执行。 / p>

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



如果还删除 static 来自初始化程序块,然后它变成一个实例初始值设定项,因此 int a 在构造时初始化。


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

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?

解决方案

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.

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".

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

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

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