使用{}括起来的代码被称为代码块。
目录
1.局部代码块;
位置:方法中的一对大括号
作用:限定变量的生命周期,提早的释放内存
package com.bingyi;
public class BlockTest {
public static void main(String[] args) {
{
int num = 10;
System.out.println(num);
}
}
}
2.构造代码块;
位置:类中方法外的一对大括号
特点:在创建对象,执行构造方法的时候,就会执行构造代码块(优先于构造方法执行)
作用:将多个构造方法,重复使用的代码,抽取到构造代码块中,从而提升代码复用性
package com.bingyi;
public class BlockTest {
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student(100);
}
}
class Student {
{
System.out.println("好好学习!");
System.out.println("天天向上!");
}
public Student() {
System.out.println("空参构造方法---");
}
public Student(int num) {
System.out.println("带参构造方法---");
}
}
3.静态代码块;
位置:类中方法外的一对大括号,需要加入static关键字
特点:随着类的加载而执行,因为类只加载一次,所以只执行一次
作用:对数据进行初始化
package com.bingyi;
public class BlockTest {
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student(100);
}
}
class Student {
static {
System.out.println("csdn----Student类的静态代码块");
}
public Student() {
System.out.println("空参构造方法---");
}
public Student(int num) {
System.out.println("带参构造方法---");
}
}
以上均来自个人学习B站黑马程序员总结