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              //执行构造代码块再执行构造方法

 

转载于:https://www.cnblogs.com/joe2047/p/9846003.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值