根据代码块定义的位置以及关键字,可以分为以下四种:
- 普通代码块
- 构造代码块
- 静态块
- 同步代码块
一、普通代码块
定义在方法中的代码块,如:
//直接使用{}定义
public class Main {
public static void main(String[] args) {
{
int x = 1;
System.out.println("x = " + x);
}
{
int y = 2;
System.out.println("y = " + y);
}
}
}
二、构造代码块
定义在类中的代码块(不加修饰符),也称实例代码块,一般用于初始化实例成员变量。如:
class Student{
private String name;
private int age;
//构造函数
public Student(){
System.out.println("we are winner");
}
//构造代码块
{
this.age = 20;
this.name = "jack";
System.out.println("I am the best");
}
public void show(){
System.out.println("name:" + name + " age:" + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.show();
}
}
输出:
I am the best
we are winner
name:jack age:20
注意:实例代码块优先于构造函数执行。
三、静态代码块
使用static定义的代码块,一般用于初始化静态成员属性。如:
class Student{
private String name;
private int age;
private static int count = 0;//静态成员变量,存于共享区
//构造函数
public Student(){
System.out.println("we are winner");
}
//构造代码块(实例代码块)
{
this.age = 20;
this.name = "Run";
System.out.println("I am the best");
}
//静态代码块
static {
count = 10;
System.out.println("I am static and count = " + count);
}
public void show(){
System.out.println("name:" + name + " age:" + age);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student();
student1.show();
student2.show();
}
}
输出:
I am static and count = 10
I am the best
we are winner
I am the best
we are winner
name:Run age:20
name:Run age:20
注意事项:
- 不管生成多少个对象,静态代码块只会执行一次,且是最先执行。
- 静态代码块执行完毕后,实例代码块(构造块)执行,再构造函数执行。