构造代码块,静态代码块,局部代码块

构造代码块

构造代码块:用一对大括号表示, 定义在类中方法外

  1. 定义位置:类中方法体
  2. 执行时机:在每个构造方法执行前执行构造代码块
  3. 作用:抽取构造方法中共性内容
package com.zqc.code_block.constructor_demo;

/**
 * 构造代码块:
 *      1.定义位置:类中方法体
 *      2.执行时机:在每个构造方法执行前执行构造代码块
 *      3.作用:抽取构造方法中共性内容
 */
public class Student {
    final int NUMBER;
    {
        NUMBER = 10;
        System.out.println("我是构造代码块。。。");
    }

    public Student() {
        //NUMBER = 10;
        System.out.println("空参构造");
    }

    public Student(int a) {
        //NUMBER = 10;
        System.out.println("有参构造");
    }
}

class Test {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student(1);
    }
}

静态代码块

  • 静态代码块 : 在一对大括号前加上static关键字 , 定义在类中方法外
  • 执行时机 : 随着类的加载而加载 , 只加载一次
  • 作用 : 一般用于给静态成员初始化
package com.zqc.code_block.static_demo;

/**
 * 静态代码块 :
 *       1 定义的位置 : 在一对大括号前加上static , 定义在类中方法外
 *       2 执行时机 ; 随着类的加载而执行, 只加载一次
 *       3 可以给类中的静态成员进行初始化数据
 */
public class Student {

    static {
        System.out.println("静态代码块");
    }

    public Student() {
        System.out.println("空参构造");
    }

    public Student(int a) {
        System.out.println("有参构造");
    }

}

class Test{
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student(1);
    }
}

 局部代码块

  • 成员代码块 : 用一对大括号表 , 可以定义在任何的局部位置 , 方法中居多
  • 执行时机 : 正常执行(从上往下依次执行)
  • 控制变量的局部变量的声明周期,变量在使用完毕后及时释放内存
package com.zqc.code_block.local_demo;

/**
 * 局部代码块 :
 *         1 位置 : 可以定义任何的局部的位置 , 方法中居多
 *         2 执行时机 : 正常执行(从上往下依次执行)
 *         3 作用 : 控制变量的生命周期 , 变量在使用完毕, 及时释放内存
 */
public class Student {

    public void show() {
        int num = 10;

        //局部代码块
        {
            int num2 = 30;
            System.out.println(num);
            System.out.println(num2);
        }

        System.out.println(num);
        //System.out.println(num2); //报错
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值