• Java面试题 静态代码块 构造代码块 构造方法 的执行顺序


    JAVA中的静态代码块 构造代码块 构造方法执行顺序:

    静态代码块(类加载时执行)>>构造代码块>>构造方法

    下面展示一个简单的例子,推荐大家动手运行一遍:

    public class Main {
    
        public static void main(String[] args) {
            son s = new son();
        }
        
    }

    /*父类*/
    public class father {
        private static String faterstaticArea = "father static area";
    
        static {
            System.out.println(faterstaticArea);
            System.out.println("father static block");
        }
    
        private String faterConstructorArea = "father Constructor area";
        {
            System.out.println(faterConstructorArea);
            System.out.println("father Constructor block");
        }
    
        father(){
            System.out.println("father constructor");
        }
    }
    //son继承father
    public class son extends father{
        private static String sonStaticArea = "son static area";
    
        static {
            System.out.println(sonStaticArea);
            System.out.println("son static block");
        }
    
        private String sonConstructorArea = "son Constructor area";
        {
            System.out.println(sonConstructorArea);
            System.out.println("son Constructor block");
        }
    
        son(){
            System.out.println("son constructor");
        }
    }
    //运行结果
    father static area  //首先加载父类
    father static block
    son static area     //加载子类
    son static block
    father Constructor area  //构造父类
    father Constructor block
    father constructor         //执行构造代码块再执行构造方法
    son Constructor area     //构造子类
    son Constructor block
    son constructor              //执行构造代码块再执行构造方法
  • 相关阅读:
    天梯赛
    CF#715 div2
    「Solution」C++ 循环结构 阶乘问题
    「ASCII Art」字符画黑人抬棺
    「Solution」P5759 [NOI1997]竞赛排名
    miller_rabin判断质数logn
    Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2) A B C 题解
    Codeforces Round #717 (Div. 2) A B C 题解
    redis php常用操作
    php7 操作MongoDB
  • 原文地址:https://www.cnblogs.com/joe2047/p/9846003.html
Copyright © 2020-2023  润新知