美文网首页
java中父子类静态代码块、非静态代码块、构造方法等的执行顺序

java中父子类静态代码块、非静态代码块、构造方法等的执行顺序

作者: mundane | 来源:发表于2022-09-12 21:36 被阅读0次
    public class Father {
    
        private int i = test();
        private static int j = method();
    
        static {
            System.out.println("father static code block");
        }
    
        Father() {
            System.out.println("father constructor");
        }
    
        {
            System.out.println("father common code block");
        }
    
        private static int method() {
            System.out.println("father static method");
            return 0;
        }
    
        public int test() {
            System.out.println("father field method");
            return 1;
        }
    }
    
    /**
     * 子类的实例化方法:
     * 1. super()
     *   1.1 父类的i = test()(被重写)
     *   1.2 父类非静态代码块
     *   1.3 父类的无参构造
     * 2. i = test()
     * 3. 子类的非静态代码块
     * 4. 子类的无参构造
     *
     */
    public class Son extends Father{
    
        private int i = test();
        private static int j = method();
    
        static {
            System.out.println("son static code block");
        }
    
        Son() {
            super();// 写或者不写都在,在子类构造器中一定会调用父类的构造器
            System.out.println("son constructor");
        }
    
        {
            System.out.println("son common code block");
        }
    
        private static int method() {
            System.out.println("son static method");
            return 0;
        }
    
        @Override
        public int test() {
            System.out.println("son field method");
            return 1;
        }
    
        public static void main(String[] args) {
            Son s1 = new Son();
            System.out.println();
            Son s2 = new Son();
        }
    }
    

    输出结果:

    father static method
    father static code block
    son static method
    son static code block // 上面这部分是类初始化
    
    son field method
    father common code block
    father constructor
    son field method
    son common code block
    son constructor
    
    son field method
    father common code block
    father constructor
    son field method
    son common code block
    son constructor
    

    解释

    1. 非静态实例变量显式赋值代码和非静态代码块代码按代码顺序从上往下执行
    2. 类变量显式赋值代码和静态代码块代码按代码顺序从上往下执行

    参考

    https://www.bilibili.com/video/BV1xt411S7xy?p=3

    相关文章

      网友评论

          本文标题:java中父子类静态代码块、非静态代码块、构造方法等的执行顺序

          本文链接:https://www.haomeiwen.com/subject/aefcortx.html