Java基础-初始化、初始块

考察知识点

  • 什么是初始块
  • 类实例化的执行过程(包括初始块)
  • 继承、覆盖的理解
/**
 * 考察类的初始化流程
 * 考察知识点1:
 *  初始代码块:
 *      静态初始代码块:static{...}
 *      非静态初始代码块:{...}
 *  执行顺序:
 *      非继承情况;
 *          静态-非静态-构造方法
 *          如果静态、非静态出现多个,则每种类型内部按定义顺序执行
 *      出现继承:
 *          父静态-子静态-父非静态-父构造-子非静态-子构造
 *          同类型多个,同上
 *  考察知识点2:
 *      继承、覆盖(覆写)
 */

代码

public class Demo{
    static class Parent {
        static {
            System.out.println("A");
        }
        {
            System.out.println("B");
        }
        static{
            System.out.println("C");
        }

        public Parent() {
            System.out.println("construct Parent.");
        }

        public void hello(){
            System.out.println("Parent.hello");
        }
    }

    static class Child extends Parent{
        static {
            System.out.println("a");
        }
        {
            System.out.println("b");
        }
        static{
            System.out.println("c");
        }

        public Child() {
            System.out.println("construct Child");
        }

        public void hello(){
            System.out.println("Child.hello");
        }
    }

    public static void main(String[] args) {
        Object child = new Child();
        Parent pp = (Parent) child;
        pp.hello();
    }
}

输出

A
C
a
c
B
construct Parent.
b
construct Child
Child.hello
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值