代码块的面试题
class Student {
static {
System.out.println("Student 静态代码块");
}
{
System.out.println("Student 构造代码块");
}
public Student() {
System.out.println("Student 构造方法");
}
}
class Demo2_Student {
static {
System.out.println("Demo2_Student静态代码块");
}
public static void main(String[] args) {
System.out.println("我是main方法");
Student s1 = new Student();
Student s2 = new Student();
}
}

1. 静态代码块:优先于主方法执行,随着类的加载而加载,且只执行一次。
2. 局部代码块:方法中出现。
3. 构造代码块:类中方法外出现,每创建一次对象就会执行一次,优先于函数执行。
本文解析了Java中不同类型的代码块(静态代码块、构造代码块和局部代码块)的执行顺序,并通过示例代码展示了这些代码块如何在类加载和对象创建过程中被执行。
16万+

被折叠的 条评论
为什么被折叠?



