java中父类和子类初始化顺序

顺序

1. 父类中静态成员变量和静态代码块

2. 子类中静态成员变量和静态代码块

3. 父类中普通成员变量和代码块,父类的构造函数

4. 子类中普通成员变量和代码块,子类的构造函数


其中“和”字两端的按照代码先后顺序执行。

举例

先看代码:

Father类

public class Father {
    public String fStr1 = "father1";
    protected String fStr2 = "father2";
    private String fStr3 = "father3";

    {
        System.out.println("Father common block be called");
    }

    static {
        System.out.println("Father static block be called");
    }

    public Father() {
        System.out.println("Father constructor be called");
    }

}
首先是Father类,该类有一个默认构造函数,有一个static的代码块,为了方便查看结果,还有一个普通代码块。

Son类

package com.zhenghuiyan.testorder;

public class Son extends Father{
    public String SStr1 = "Son1";
    protected String SStr2 = "Son2";
    private String SStr3 = "Son3";

    {
        System.out.println("Son common block be called");
    }

    static {
        System.out.println("Son static block be called");
    }

    public Son() {
        System.out.println("Son constructor be called");
    }

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

}

Son类的内容与Father类基本一致,不同在于Son继承自Father。该类有一个main函数,仅为了测试用,不影响结果。

在main函数中实例化Son。

结果为:

Father static block be called
Son static block be called
Father common block be called
Father constructor be called
Son common block be called
Son constructor be called

Father common block be called
Father constructor be called
Son common block be called
Son constructor be called

总结:

1,在类加载的时候执行父类的static代码块,并且只执行一次(因为类只加载一次);

2,执行子类的static代码块,并且只执行一次(因为类只加载一次);

3,执行父类的类成员初始化,并且是从上往下按出现顺序执行(在debug时可以看出)。

4,执行父类的构造函数;

5,执行子类的类成员初始化,并且是从上往下按出现顺序执行。

6,执行子类的构造函数。

欢迎转载,请标明出处:http://blog.csdn.net/yuxin6866/article/details/53107578


  • 12
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值