When are Java_classes loaded (demonstrated with code blocks)

in conclusion

1. When creating an object instance (new)

2. Create a subclass object instance, and the parent class will also be loaded

3. When using static members of a class (static properties, static methods)

directly on the code

public class CodeBlockDetail01 {
    public static void main(String[] args) {
        BB bb = new BB();
        System.out.println(Cat.n1);
    }
}
class Cat{
    public static int n1 = 888;
    static {
        System.out.println("Cat的静态代码块被被调用");
    }
}
class AA{
    {
        System.out.println("AA类被加载");
    }
}
class BB extends AA{
    {
        System.out.println("BB类被加载");
    }
}

 The result of the operation is as follows:

AA class is loaded
BB class is loaded
Cat's static code block is called
888

Guess you like

Origin blog.csdn.net/ming2060/article/details/127800424