[Turn] java understands static code blocks

Original address: https://blog.csdn.net/lxyzhu/article/details/41041641

A static code block is generally used to initialize static variables in a class. The static code block is executed during the initialization phase of the class loading process and is executed only once.


Initializing with a static block is the same as initializing the variable directly when defining it, but their order may affect the value of the variable.

Example:
public class TestStatic {
    public static int a = 1;
    public static int b = 3;
    public static String str;

    static {
        str = "i am here";
        a = 10;
        b = 30;
    }

    public static void main(String[] args) {
        System.out.println(TestStatic.str);
        System.out.println(TestStatic.a);
        System.out.println(TestStatic.b);
    }
}
output:
i am here
10
30

The above output shows that the initialization operation in the static static code block overrides the initialization operation when the variables are defined, that is, they are initialized in the order written in the code, so the subsequent assignment operation will overwrite the previous value.

If you change the above code to this:
public class TestStatic {
    static {
        str = "i am here";
        a = 10;
        b = 30;
    }
    public static int a = 1;
    public static int b = 3;
    public static String str;

    public static void main(String[] args) {
        System.out.println(TestStatic.str);
        System.out.println(TestStatic.a);
        System.out.println(TestStatic.b);
    }
}
The output becomes:
i am here
1
3

This shows that our conclusion above is correct.


Additional instructions:

In fact, the static static code block can be regarded as a static method with no name, no parameters and no return value . This static method will be executed before the main method is executed, and it is executed actively, without any display call, other than that In addition, it is no different from a normal static method, so the rules that apply to normal static methods also apply to this static static code block, such as:
 
1. 无法在静态方法里引用实例变量、也无法调用实例方法,但是可以调用静态变量和静态方法,你甚至可以在static静态代码块里调用main方法,都是没有问题的

2. 无法在静态方法里使用this关键字和super关键字(因为this关键字指向该方法所属的对象,而静态方法是属于类级的,不存在对象一说;至于super关键字,只要不是用在构造方法里,那么 
   它 就是指向父类对象的,而静态方法是不能引用实例对象的,因此也不能使用super关键字)

3. 无法在静态方法里声明其他静态变量(其实这一点不只是静态方法才适用,包括实例方法也无法在方法体中声明静态变量,因为静态变量属于类变量)

4. 无法在静态方法里使用域修饰符来声明变量:public、protected、private,只能使用默认的访问域(这一点实例方法 也是适用的


感觉博主写的很好,有更易理解的想法,欢迎大家评论里写出

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325842536&siteId=291194637