------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
代码块就是用{ } 括起来的代码段。
java中代码块分为三种:局部代码块、构造代码块和静态代码块。
一:局部代码块
在方法中,主要用于限定变量的生命周期。
public void show(){
int a=0;
{
int a=1;
}
System.out.println(a);
}
public static void main(String[] args){
show();
}
输出结果是什么呢?
答案是:0
应为虽然第二次为a赋值为1,但是这个a的生命周期在出现“ } ” 时候就已经结束了。故a还是0.
二。构造代码块
在类中方法外的成员位置。每次调用构造方法前,都调用构造代码块。而且执行顺序总是先构造代码块,后构造方法,与书写位置无关。
可以将多个构造方法中相同的代码放到一起。
三:静态静态代码块
在类中方法外的成员位置,用static 修饰。特点是只执行一次,而且在构造代码块之前执行,与书写位置无关。一般用于对类进行初始化。
class Student4{
static{
System.out.println("student static 静态代码块 ");
}
{
System.out.println("student 构造代码块");
}
public Student4(){
System.out.println("student 构造方法");
}
}
class StudentDemo4{
static{
System.out.println("我是静态代码块");
}
}
public class Test09 {
static{
System.out.println("我是static");
}
public static void main(String[] args) {
System.out.println("我是main");
Student4 s1=new Student4();
Student4 s2=new Student4();
}
}
执行结果是:
我是static
我是main
student static 静态代码块
student 构造代码块
student 构造方法
student 构造代码块
student 构造方法