1 代码块
代码块是指使用了“{}”定义的一段程序代码,代码块根据其定义的位置以及声明的关键字的不同可以分为四类:普通代码块、构造块、静态块、同步代码块。
1.1 普通代码块
指的是定义在方法中的代码块。
范例:观察一个程序
代码
public class TestDemo {
public static void main(String[] args){
if (true){ // 表示该判断一定成立
int x= 10;
System.out.println("x = " + x);
}
int x = 100;
System.out.println("x = " + x);
}
}
输出结果
x = 10
x = 100
把if语句去掉就是普通代码块。
如果现在的方法代码过长,又要避免变量重名问题,可以使用普通代码块。
1.2 构造块
指的是定义在类中的代码块。
范例:定义构造块
代码
class Person{
{
System.out.println("1. Person类的构造块");
}
public Person(){
System.out.println("2. Person类的构造方法");
}
}
public class TestDemo {
public static void main(String[] args){
new Person();
new Person();
}
}
输出结果
1. Person类的构造块
2. Person类的构造方法
1. Person类的构造块
2. Person类的构造方法
每次使用关键字new实例化对象时一定会调用构造方法,有构造块后,构造块优先于构造方法执行。使用构造块可以进行一些简单的逻辑操作。
代码
class Person{
private String info = "hello";
{ // 在构造块里先进行一些处理
for (int x = 0; x < 10; x++) {
info += x;
}
}
public Person(){
System.out.println("Person类的构造方法" + info);
}
}
public class TestDemo {
public static void main(String[] args){
new Person();
new Person();
}
}
输出结果
Person类的构造方法hello0123456789
Person类的构造方法hello0123456789
1.3 静态代码块
指的是使用了static关键字定义的代码块:
- 在非主类中定义的静态块;
- 在主类中定义的静态块。
范例:观察静态块定义
class Person{
{
System.out.println("1. Person类的构造块");
}
public Person(){
System.out.println("2. Person类的构造方法");
}
static{
System.out.println("3. Person类的静态块");
}
}
public class TestDemo {
public static void main(String[] args){
new Person();
new Person();
}
}
输出结果
3. Person类的静态块
1. Person类的构造块
2. Person类的构造方法
1. Person类的构造块
2. Person类的构造方法
静态块执行优先于构造块,不管产生多少个实例化对象,静态块只执行一次,它最为主要的作用是给static属性初始化。
代码
class Person{
private static String info = "Hello";
{
System.out.println("1. Person类的构造块");
}
public Person(){
System.out.println("2. Person类的构造方法");
}
static{ // 静态块
info += " World!!!"; // 对static进行初始化配置
System.out.println("3. Person类的静态块" + info);
}
}
public class TestDemo {
public static void main(String[] args){
new Person();
new Person();
}
}
输出结果
3. Person类的静态块Hello World!!!
1. Person类的构造块
2. Person类的构造方法
1. Person类的构造块
2. Person类的构造方法
静态块也可以定义在主方法中,此时静态块经将优先于主方法执行。
代码·
public class TestDemo {
public static void main(String[] args){
System.out.println("Hello World!!!");
}
static {
System.out.println("***************************");
}
}
输出结果
***************************
Hello World!!!
2 总结
如果需要在一些属性使用前做处理就使用构造块或者静态块。