Java静态字段用法

Ism*_*hin 3 java static

我申请了一份工作,他们给了我一个java测试.有许多我不熟悉的未知概念,也有较新的概念.一个是静态场.我发布了下面最奇怪的问题之一并寻求帮助.

代码包含注释中的问题.

public class MyClass {

    //what is the purpose of section, I mean for which purpose is it being used?
    //can variables inside of belove section be used or not. If can be used, then how?
    static{ 
        int a=5;
        double x=4.1;
    }

    //why this does not give any error because of redecleration of integer a?
    static int a=4;

    public static void main(String[] args) {
        System.out.println(a+"");//the output is 4
    }

}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

这个块

static{ 
    int a=5;
    double x=4.1;
}
Run Code Online (Sandbox Code Playgroud)

被称为静态初始化器.static当初始化字段可能需要多个语句时,它用于初始化字段.

但是在这里,你实际上并没有初始化任何静态变量.您刚刚声明了两个局部变量.

这是重要的一行:

static int a=4;
Run Code Online (Sandbox Code Playgroud)