Java中类的初始化顺序

先写代码分析,以后再补文章内容

父类:

package cn.tom.init;

/**
 * Created by lenovo on 2017/3/8.
 */
public class ParentInit {

    private static String parentStr = "我是静态字符串parentStr";
    private String parentStr2 = "我是字符串parentStr";

    public ParentInit() {
        System.out.println("我是构造器ParentInit" + "---------" + 7);
    }

    static {
        System.out.println("静态代码块中===" + parentStr + "----------" + 1);
        System.out.println("我是静态代码块ParentInit" + "---------" + 2);
    }

    {
        System.out.println(parentStr2 + "-----------" + 5);
        System.out.println("我是代码块ParentInit" + "----------" + 6);
    }

    static void get() {
        System.out.println("我是静态方法ParentInit" + "-----------" + 11);
    }

    void query() {
        System.out.println("我是方法ParentInit");
    }
}
子类:

package cn.tom.init;

/**
 * Created by lenovo on 2017/3/8.
 * 类的初始化顺序
 */
public class ChildInit extends ParentInit {

    private static String childStr = "我是静态字符串childStr";
    private String childStr2 = "我是字符串childStr";

    public ChildInit() {
        System.out.println("我是构造器ChildInit" + "----------" + 10);
    }

    static {
        System.out.println("静态代码块" + childStr + "---------" + 3);
        System.out.println("我是静态代码块ChildInit" + "----------" + 4);
    }

    {
        System.out.println("代码块中" + childStr2 + "----------" + 8);
        System.out.println("我是代码块ChildInit" + "-----------" + 9);
    }

    static void get() {
        System.out.println("我是方法ChildInit");
    }

    @Override
    void query() {
        System.out.println("我是方法ChildInit" + "--------" + 12);
    }

    public static void main(String[] args) {
        ParentInit parentInit = new ChildInit();
        parentInit.get();//此处调用的是父类的,静态方法不能重写
        parentInit.query();//此处调用时子类的
    }
}
运行效果:

由以上得出结论:

1、父类的【父类静态变量】>【父类静态代码块】>【子类静态变量】>【子类静态代码块】>【父类成员变量】>【父类代码块】>【父类构造器】>【子类成员变量】>【子类代码块】>【子类构造器】

2、子类不能重写父类的静态方法



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值