一、普通代码块
普通代码块就是直接在方法或语句中定义的代码块
public class Test{
public static void main(String[] args) {
{
int x = 30;
System.out.println("普通代码块:x = " + x);
}
int x = 100;
System.out.println("代码块之外:x = " + x);
}
}
class Demo{
{
System.out.println("1. 构造块。");
}
public Demo(){
System.out.println("https://cdn.jxasp.com:9143/image/2. 构造方法。");
}
}
public class Test{
public static void main(String[] args) {
{
new Demo();
new Demo();
new Demo();
}
}
}
- 11
- 12
- 13
- 14
- 15
- 16
- 17
构造块优先于构造方法执行,而且每次实例化对象的时候都会执行构造块中的代码,会执行多次
三、静态代码块
静态代码块,是使用 static 关键字声明的代码块
class Demo{
{
System.out.println("1. 构造块。");
}
static {
System.out.println("0. 静态代码块");
}
public Demo(){
System.out.println("https://cdn.jxasp.com:9143/image/2. 构造方法。");
}
}
public class Test{
static {
System.out.println("在主方法所在类中定义的代码块");
}
public static void main(String[] args) {
{
new Demo();
new Demo();
new Demo();
}
}
}
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
静态代码块优先于主方法执行,而在类中定义的静态代码块会优先于构造块执行,而且不管有多少个对象产生,静态代码块只执行一次。