"{}"定义的结构就为代码块。根据代码块出现的位置以及定义的关键字的不同,代码块可以分为: 普通代码块, 构造代码块, 静态代码块,同步代码块。
同步代码块
在一些方法之中进行结构的拆分,以防止相同变量带来的影响。
public class JavaDemo {
public static void main(String[] args) {
{
int x=1;
System.out.println("x="+x);
}
int x=0;
System.out.println("x="+x);
}}
构造代码块
class Person{
public Person(){
System.out.println("构造方法"); }
{
System.out.println("构造块");
}}
public class JavaDemo {
public static void main(String[] args) {
new Person();
}}
程序截图:
构造块会优先于构造方法执行,并且每一次实例化新对象都会调用构造块中的代码。
静态代码块
使用static关键字定义的代码块,分为主类定义的代码块和非主类的代码块。
非主类
class Person{
public Person(){
System.out.println("构造方法"); }
static{
System.out.println("静态块");}
{
System.out.println("构造块");
}}
public class JavaDemo {
public static void main(String[] args) {
new Person();
new Person();
new Person();
}}
程序截图:
静态块优先于构造块执行,并且不管有几个实例化对象出现,静态块都只会执行一次。
主类
public class JavaDemo {
static{
System.out.println("hello"); }
public static void main(String[] args) {
System.out.println("xiatian");
}}
程序截图:
静态代码块优先于主方法先执行。