Java中的代码块
Java中有三种代码块:
- 1.普通代码块(在方法内)
- 2.构造代码块(在方法外,在类内)
- 3.静态代码块(在方法外,在类内,带static关键字)
1.普通代码块:
一般称它为成员代码块,其作用与局部变量相同,但是在这种代码块中声明的局部变量离开 代码块运行的范围内其生命期就会结束。我们一般会用它来节省开销。需要注意的是代码块中声明的变量名不能与代码块外的变量名重复。
例子:
public class BlockTest{
public static void main(String[] args)
{
{
int x = 10; // x 的生命期开始
System.out.println(x);
x += 5;
System.out.println(x);
}// x 的生命期结束
代码块外便无法访问x
}
}
2.构造代码块:
构造代码块出现在该类中,该类的其他方法外。在每次创建一个该类的对象时,都会优先先执行这个代码块中的内容。
例子:
public class Student{
String name;
int age;
Student()
{
}
Student(String name,int age)
{
this.name = name;
this.age = age;
}
{
//每次新创建一个Student类的对象时都会先执行块中内容,即先打印这句话
System.out.println("构造代码块");
}
}
构造代码块的简单运用:
我们可以运用构造代码块和静态成员变量来统计一共创建过多少个该类对象
public class Student{
String name;
int age;
static int times = 0;
Student()
{
}
Student(String name,int age)
{
this.name = name;
this.age = age;
}
{
//每次新创建一个Student类的对象时都会先执行块中内容,即先打印这句话
times ++;
System.out.println("构造代码块: " + times);//统计创建数
}
}
3.静态代码块
静态代码块与构造代码块类似,但不同的是它仅在类加载时执行一次,即多次创建该类对象 静态代码块也只执行一次,且如果放在主方法外,静态代码块优先于主方法执行。
由于静态代码块只执行一次的特点,一般用于加载驱动和进行一些初始化。
例子:
public class Student{
String name;
int age;
Student()
{
}
Student(String name,int age)
{
this.name = name;
this.age = age;
}
static{
System.out.println("初始化完成");//整个程序仅执行一次
}
}