您的位置:首页 > 编程语言 > Java开发

JAVA中代码块

2017-08-24 10:14 106 查看
1 普通代码块

为了防止在方法里面编写的代码的变量重名,对一个方法进入一个局部的分割,但是基本上没有什么意义。因为一个方法的代码不会写得很长,同时我们在对变量的命名的时候都是有意义的定义。

定义如下:

public static void main(String[] args) {
{	// 普通代码块
int num = 10 ; 	//局部变量
System.out.println("num = " + num); // 10
}
int num = 100 ; 	//全局
System.out.println("num = " + num); // 100
}


2 构造块

将一个代码块写在一个类里面

运行方法:

public static void main(String[] args) {
new Book();
}


Book类:

package com.test;

public class Book {
public Book() {
System.out.println("Book类的构造方法");
}

{	//代码块写在类里面
System.out.println("Book类的构造块");
}

}


运行结果:



我们发现构造块先运行,产生多个对象,构造块会出现多次。

3 静态块

如果代码块使用了static进行定义的话,那么就称它为静态块,有两种使用的情况

情况1: 在非主类中使用:

运行方法:

public static void main(String[] args) {
new Book();
new Book();
new Book();
}


Book类

package com.test;

public class Book {
public Book() {
System.out.println("Book类的构造方法");
}

{	//代码块写在类里面
System.out.println("Book类的构造块");
}
static {
System.out.println("Book类的静态块");
}

}


运行结果:



从运行结果,我们可以看出,静态块的优先级高于构造块与构造方法。静态块一般是给静态属性初始化,但是使用比较少。

情况二:在主类中定义

static{
System.out.println("***********");
}

public static void main(String[] args) {
System.out.println("Hello World!");
}


运行结果:



静态块优先于主方法执行。在JDK1.7之前,可以没有主方法也能运行,只要有一个静态块也能运行,但是在1.7之后,这个BUG已经修复。

4总结

代码块能不用就不用,在编写测试可以使用静态块来做一些数据的初始化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息