在Java学习中,我们会见到代码块的存在。所谓代码块就是被一对{}大括号所括起来的代码。
根据代码块定义位置的不同,我们可以将代码块分为局部代码快、构造代码块以及静态代码块。
1.局部代码块
public class MyTest {
public static void main(String[] args) {
//局部代码块:定义在类中方法外的代码块
{
int num=100;
System.out.println("局部代码块"+num);
}
}
}
输出的结果为:
局部代码块100
局部代码块:定义在方法中的代码块,有利于代码中资源的及早释放
2.构造代码块
public class MyTest1 {
public static void main(String[] args) {
//构造代码块,每次创建对象时,就会执行,而且优先于构造的方法之前执行
Star star = new Star();
Star star1 = new Star();
}
}
class Star{
//构造代码块
{
System.out.println("构造代码块,定义在类中方法外的代码块");
}
//构造方法
public Star(){
System.out.println("空参构造执行了");
}
}
运行后的结果为:
构造代码块,定义在类中方法外的代码块
空参构造执行了
构造代码块,定义在类中方法外的代码块
空参构造执行了
构造代码块:定义在类中方法外的代码块,每次创建对象都会进行调用,优先于构造的方法调用。
3.静态代码块
public class Test {
public static void main(String[] args) {
Student student = new Student();
Student student1 = new Student();
}
}
class Student{
//构造代码块
{
System.out.println("构造代码块,定义在类中方法外的代码块");
}
//静态代码块
/*静态代码块随着类的加载而加载,最先执行
且执行一次(.class文件只能加载一次)
静态代码块中只能访问静态成员
*/
static {
System.out.println("静态代码块,被static所修饰的代码块");
}
public Student(){
System.out.println("空参构造执行了 ");
}
}
运行后的结果为:
静态代码块,被static所修饰的代码块
构造代码块,定义在类中方法外的代码块
空参构造执行了
构造代码块,定义在类中方法外的代码块
空参构造执行了
静态代码块:被static所修饰的代码块,随着类的加载而加载,且执行一次,静态代码块只能访问静态成员
代码块之间区别与执行顺序的练习:
class Student{
static{
System.out.println("Student 静态代码块");//3
}
{
System.out.println("Student 构造代码块");//4 //6
}
public Student(){
System.out.println("Student 构造方法");//5 //7
}
}
public class StudentDemo {
static {
System.out.println("StudentDemo 静态代码块");//1
}
public static void main(String[] args) {
System.out.println("我是main方法");//2
Student student = new Student();
Student student1 = new Student();
}
}
运行后的的结果为:
StudentDemo 静态代码块
我是main方法
Student 静态代码块
Student 构造代码块
Student 构造方法
Student 构造代码块
Student 构造方法