java static static blocks, common blocks, static properties, internal class, the internal static class, subclass inside, building blocks, the execution order of initialization Analysis Example

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/c5113620/article/details/89740838

Because where the main class in the jvm will start automatically loaded , so write in another class to do the test.

//Test.java
public class Test {
    public static void main(String[] args) {
        new People();
        new People();
//        System.out.println(People.name);

//        People.test();

//        System.out.println(People.Head.name);
    }
}
public class People {
    {
        System.out.println("111");
    }
    static {
        System.out.println("3");
        name="3";
    }
    public static String name="1";

    static {
        System.out.println("2");
        name="2";
    }

    public static void test(){
        System.out.println("test");
    }

    static class Head{
        public static String name="head1";
        static {
            System.out.println("head2");
            name="head3";
        }
    }

    {
        System.out.println("222");
    }

    class Body{

    }
}

class Child extends People{
    
}

  1. Static blocks (or building blocks) with regular block
静态块,加载类时(读取类编译的class文件时)执行【一次】
常用作初始化静态属性,因为静态属性只能做简单赋值,比如基本类型或者new,不能写多行代码复杂赋值
static {
}
没有static是普通块,对象【每次】new会执行
{
}
  1. Static block execution order static attribute, performed in accordance with the order of the code, the class file is loaded class, like the head through the file execution sequence] [static or static property assignment block
System.out.println(People.name)
输出最下面静态块的值 2
  1. Regardless of the internal class is a normal class or static classes, subclasses or internal, will be compiled into [ alone ] class files, so you can think of, direct access to static inner classes [ not load external class class], direct access to the outer class static method, [ not load the inner class class]
People.test();  //没有初始化内部静态类
System.out.println(People.Head.name); //没有初始化外部类

Here Insert Picture Description
[ Summary ]

  1. When jvm will need this class, to load class files compiled after the class, the class has a separate internal document storage, but a special name. After reading the class jvm class performs a static block in accordance with the order of the code static properties. Static blocks are mainly used to initialize static properties
  2. A jvm will start the same class file loaded once when the class is not quoted, when gc starts, recover memory

Guess you like

Origin blog.csdn.net/c5113620/article/details/89740838