Java代码块(静态和非静态)在子父类中的执行顺序

举报
YuShiwen 发表于 2022/03/30 23:11:16 2022/03/30
【摘要】 话不多说,直接上代码: /** * @Author: YuShiwen * @Date: 2020/11/17 9:01 PM * @Version: 1.0 */ class Root{ ...

话不多说,直接上代码:

/**
 * @Author: YuShiwen
 * @Date: 2020/11/17 9:01 PM
 * @Version: 1.0
 */

class Root{
    static{
        System.out.println("Root static block");
    }
    {
        System.out.println("Root no static block");
    }
    public Root(){
        super();
        System.out.println("Root no parameter");
    }
}

class Mid extends Root{
    static{
        System.out.println("Mid static block");
    }
    {
        System.out.println("Mid no static block");
    }
    public Mid(){
        super();
        System.out.println("Mid no parameter");
    }

    public Mid(String msg){
        this();
        System.out.println("Mid constructor:"+msg);
    }
}

class Leaf extends Mid{
    static{
        System.out.println("Leaf static block");
    }
    {
        System.out.println("Leaf no static block");
    }
    public Leaf(){
        super("YuShiwen");
        System.out.println("Leaf no parameter");
    }
}

public class LeafTest {
    public static void main(String[] args) {
        new Leaf();
        System.out.println();
        new Leaf();
    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

输出结果:

Root static block
Mid static block
Leaf static block
Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Root no static block
Root no parameter
Mid no static block
Mid no parameter
Mid constructor:YuShiwen
Leaf no static block
Leaf no parameter

Process finished with exit code 0


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

代码分析:
可以看出,静态代码块内的语句由父类到子类最先执行,且只执行一次,这是因为静态代码块虽类的加载而加载;
之后每创建一次对象的时候,由父及子,先执父类中的普通代码块,再执行父类中的构造器,然后在执行子类中的普通代码块,再执行子类中的构造器。

文章来源: blog.csdn.net,作者:Mr.Yushiwen,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/MrYushiwen/article/details/109754257

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。