JAVA代码块
什么是代码块
代码块就是被一对{ } 所括起来的内容
代码块的分类
根据代码块定义的位置不同,我们可以将代码块分为局部代码块,构造代码块,静态代码块,同步代码块(多线程)。
局部代码块:定义在方法中的代码块。
静态代码块:位于类中,用static 所修饰的代码块。
构造代码块,每次创建对象时都会执行,优先于构造方法执行。
代码块的执行顺序
main方法在运行时会先执行该类的静态代码块。
创建一个类对象时会先执行静态代码块,且只有在第一次创建该类对象时会执行。其次会执行构造代码块,且构造代码块会在构造方法前执行。在运行到一个函数时,才会执行该函数的局部代码块。
class Student2 {
static {
System.out.println("Student 静态代码块");
}
{
System.out.println("Student 构造代码块");
}
public Student2() {
System.out.println("Student 构造方法");
}
}
public class StudentDemo {
static {
System.out.println("StudentDemo的静态代码块");
}
public static void main(String[] args) {
System.out.println("我是main方法");
Student2 s1 = new Student2();
Student2 s2 = new Student2();
}
}
执行结果为