码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-24 22:07:03      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:展示   lock   ora   java面试   color   执行   加载   extend   静态代码块   

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

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

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

public class Main {

    public static void main(String[] args) {
        son s = new son();
    }
    
}
//运行结果
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              //执行构造代码块再执行构造方法

 

/*父类*/
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");
    }
}

 

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

标签:展示   lock   ora   java面试   color   执行   加载   extend   静态代码块   

原文地址:https://www.cnblogs.com/joe2047/p/9846003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!