本文最后更新于2022年6月1日,已超过 1 年没更新!内容可能已失效,请自行测试。
在程序中使用{}定义的的结构就称为代码块,而后根据代码块出现的位置以及定义的关键字不同,可分为:普通代码块,构造代码块,静态代码块,同步代码块.其中同步代码块是在多线程方面
普通代码块
普通代码块的主要特点是定义在一个方法中中的代码块
public class CodeDemo {
public static void main(String[] args) {
{
int x = 10; // 局部变量
System.out.println("x=" + x);
}
int x = 100; // 全局变量
System.out.println();
System.out.println("x=" + x);
}
}
构造代码块
class personcode {
public personcode() {
System.out.println("[构造块]personcode构造方法执行");
}
{
System.out.println("[构造块]personcode构造块执行");
}
}
public class CodeDemo2 {
public static void main(String[] args) {
new personcode();
new personcode();
new personcode();
}
}
构造块会优先于构造方法执行,并且每一次实例化新对象的时候都会调用构造块中的代码
静态代码块
静态代码块主要指的是使用static关键字定义的代码块,静态块的定义需要考虑到两种情况:主类定义静态块和非主类定义静态块
// 非主类中定义
class personcode2 {
public personcode2() {
System.out.println("[构造块]personcode构造方法执行");
}
static {
System.out.println("[静态块]静态块执行");
}
{
System.out.println("[构造块]personcode构造块执行");
}
}
public class CodeDemo3 {
public static void main(String[] args) {
new personcode2();
new personcode2();
new personcode2();
}
}
静态代码块会优先于构造块执行,且只执行一次.主要目的是为类中的静态属性初始化
public class CodeDemo5 {
static {
System.out.println("*****************");
}
public static void main(String[] args) {
System.out.println("YES");
}
}
静态代码块优先于主方法执行
Comments | NOTHING
Warning: Undefined variable $return_smiles in /www/wwwroot/blog.yeyufan.cn/wp-content/themes/Aurore/functions.php on line 1096