1. package test;
    2. class Person {
    3. public static int total;//静态变量
    4. static {//静态代码块
    5. total = 100;
    6. System.out.println("in static block!");//(1)
    7. }
    8. }
    9. class Test {
    10. public static void main(String[] args) {
    11. System.out.println("total = " + Person.total); //100
    12. System.out.println("total = " + Person.total); //100
    13. }
    14. }

    image.png

    1. package test;
    2. public class Main {
    3. //主方法
    4. public static void main(String str[]) {
    5. Test a = new Test();//无参构造器
    6. }
    7. }
    8. class Sample {
    9. Sample(String s) {
    10. System.out.println(s);
    11. }
    12. }
    13. class Test {
    14. Sample sam1 = new Sample("sam1成员初始化");
    15. static Sample sam = new Sample("静态成员sam初始化 ");
    16. static {
    17. System.out.println("static块执行");
    18. if (sam == null) {
    19. System.out.println("sam is null");
    20. }
    21. }
    22. Test() {//构造器
    23. System.out.println("Test默认构造函数被调用");
    24. }
    25. }

    image.png