JavaSE基础之代码块

Java将被 { } 包裹的部分称之为代码块。但是这部分知识在开发中很少被使用到,不过大家在面试过程中可能会被这个小东西虐到。

  • 分类

根据代码块的位置与声明的不同,可分为局部代码块构造代码块静态代码块 以及 同步代码块

  • 区别及代码演示
  1. 局部代码块
    写在方法中的变量我们叫做局部变量,同样,写在方法中的代码块我们叫做局部代码块,它的用途不广,我了解仅限其用于限制变量的生命周期。

    public void method() {
        {
             int x = 10;
             System.out.println("x的值为" + x);
        }
             System.out.println("x的值为" + x);
    } 
    

    以上的方法会在执行输出一个x的值为10之后向我们抛出一个错误找不到符号x变量x只能在局部块中使用,局部块执行完毕,x就被销毁,就如同在for循环中定义的循环变量一般。

  2. 构造代码块
    写在类中方法外的代码块被称之为构造代码块,它在会在执行该类构造方法的时候被执行。也就是说,多次执行构造方法就会多次执行构造代码块。

public class Student {
    private int age;
    {
         System.out.println("我是构造代码块!!");
    }
    public Student() {
         System.out.println("我是无参构造!!");
    }
    public Student(int age) {
         this.age = age;
         System.out.println("我是有参构造!!");
    }
} 

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

输出结果:

我是构造代码块!!
我是无参构造!!
我是构造代码块!!
我是有参构造!!

我们能够很清楚的看见构造代码块是优先于构造方法执行的。

  1. 静态代码块
    被加了static修饰的代码块我们称之为静态代码块,静态代码块回在类被加载入方法区的时候被执行一次。往后不再执行。
public class Student {
    private int age;
    static {
         System.out.println("我是静态代码块!!");
    }
    public Student() {
         System.out.println("我是无参构造!!");
    }
    public Student(int age) {
         this.age = age;
         System.out.println("我是有参构造!!");
    }
} 
public class MainClass {
    public static void main(String[] args) {
         Student s1 = new Student();
         Student s2 = new Student(15);
    }
}

输出结果:

我是静态代码块!!
我是无参构造!!
我是有参构造!!

静态代码块仅仅执行了一遍。

注意:
静态代码块和构造代码块都是先于构造方法执行,那么他们之间又是谁先谁后呢?其实我已经再文中做了介绍,不知道大家有没有注意到
构造代码块是在执行构造方法时被先一步执行
静态代码块是在类加载时就被执行
自然两者之间是静态代码块先被执行。

  1. 同步代码块
    待以后更新到多线程时再做详解。
  • 那么问题来了!!
class Student {
    static {
        System.out.println("Student 静态代码块");
    }
    
    {
        System.out.println("Student 构造代码块");
    }
            
    public Student() {
        System.out.println("Student 构造方法");
    }
}
    
class MainClass {
    static {
        System.out.println("MainClass静态代码块");
    }
            
    public static void main(String[] args) {
        System.out.println("我是main方法");
                
        Student s1 = new Student();
        Student s2 = new Student();
    }
}

它的输出结果是什么?

你可能感兴趣的:(JavaSE基础之代码块)