zoukankan      html  css  js  c++  java
  • 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              //执行构造代码块再执行构造方法
  • 相关阅读:
    P3381 【模板】最小费用最大流
    Android Studio安装插件提示was not installed: Cannot download的解决
    webpack 引用vconsole
    vue ...mapMutations 的第一个参数默认为 数据对象state
    vue 如何实现在函数中触发路由跳转
    axios 使用
    rem 的使用
    vscode 习惯配置
    修改默认的inout输入框背景颜色
    vue -本地服务配置
  • 原文地址:https://www.cnblogs.com/joe2047/p/9846003.html
Copyright © 2011-2022 走看看