Java继承——代码块与构造器

示例

class Parent {
    static {
        System.out.println("Parent's static code block...");
    }

    {
        System.out.println("Parent's constructor code block...");
    }

    public Parent() {
        System.out.println("Parent's constructor without arguments...");
    }

}

class Children extends Parent {
    private String name;

    static {
        System.out.println("Children's static code block...");
    }

    {
        System.out.println("Children's constructor code block...");
    }

    public Children() {
        System.out.println("Children's constructor without arguments...");
    }

    public Children(String name) {
        this.name = name;
        System.out.println("Children's constructor with arguments...");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

public class ExtendTest {

    public static void main(String[] args) {
        /*
         * ExtendTest's static code block is executed...
         * Parent's static code block...
         * Parent's constructor code block...
         * Parent's constructor without arguments...
         * ------------------------
         * Parent's constructor code block...
         * Parent's constructor without arguments...
         */
        /*Parent p1 = new Parent();
        System.out.println("------------------------");
        Parent p2 = new Parent();*/

        /*
         * ExtendTest's static code block is executed...
         * Parent's static code block...
         * Children's static code block...
         * Parent's constructor code block...
         * Parent's constructor without arguments...
         * Children's constructor code block...
         * Children's constructor without arguments...
         * ------------------------
         * Parent's constructor code block...
         * Parent's constructor without arguments...
         * Children's constructor code block...
         * Children's constructor with arguments...
         */
        Children c1 = new Children();
        System.out.println("------------------------");
        Children c2 = new Children("Bob");
    }

    static {
        System.out.println("ExtendTest's static code block is executed...");
    }
}

总结

静态代码块:
1. 静态代码块只能在类中由static{}进行声明创建,不能放在类中的方法中或其他代码块中
2. 静态代码块属于类,在类被JVM加载时被执行,只会执行一次
3. 静态代码块先于main()方法执行
4. 静态代码块用于给类初始化
构造代码块
1. 构造代码块只能在类中由{}进行声明创建,若放在类中的方法中或其他代码块中,则称之为“局部代码块”
2. 构造代码块会在创建对象时,先于构造器执行
3. 构造代码块用于给对象进行统一初始化

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值