Java 中的静态块

10 Sept 2024 | 4 分钟阅读

当一个代码块被“static”关键字修饰或与之关联时,它被称为静态代码块。静态代码块也称为静态子句。静态代码块可用于类的静态初始化。在类加载到内存时,静态代码块中的代码会执行一次。

调用静态代码块

现在的问题是,如何调用静态代码块?调用静态代码块没有特定方法,因为每当类加载到内存时,静态代码块就会自动执行。请观察以下插图。

文件名: StaticBlock.java

输出

Inside the static block.
Inside the constructor of the class.
Inside the print method.
Inside the constructor of the class.

解释:从输出可以看出,静态代码块的打印语句首先执行。然后,类的构造函数的打印语句执行,接着是 print() 方法的打印语句,然后再次是构造函数的打印语句。此外,请注意,在 main() 方法中,我们显式调用了类的构造函数和 print() 方法。然而,没有为调用静态代码块编写任何语句。这表明静态代码块是自动执行的,而且是在调用类的构造函数之前执行的。

示例 - 1

让我们看一个例子来更好地理解静态代码块。

文件名: StaticBlock1.java

输出

Inside the static block. - 1
Inside the static block. - 2
Inside the static block. - 3
Inside the constructor of the class.
Inside the method foo.
Inside the constructor of the class.

解释:从输出可以看出,静态代码块首先执行,而且是按照代码中编写的静态代码块的顺序执行的。还可以看出,代码中可以存在多个静态代码块。

示例 - 2

让我们看另一个静态代码块的例子。

文件名: StaticBlock2.java

输出

/StaticBlock2.java:21: error: non-static method foo() cannot be referenced from a static context
foo();
^
/StaticBlock2.java:22: error: non-static variable st cannot be referenced from a static context
System.out.println(st);
                   ^
2 errors

解释:静态代码块只能访问静态变量或静态方法,如果尝试访问任何非静态变量/方法,则会报错。

为了使程序无错误地运行,请为变量 st 和方法 for 添加关键字 static,如下面的程序所示。

文件名: StaticBlock3.java

输出

Inside the method foo.
9
Inside the static block. - 1
Inside the constructor of the class.

静态代码块和 Main 方法

我们知道,当类加载时,静态代码块会自动加载(请参阅上面的示例)。换句话说,不需要方法来调用静态代码块。那么问题来了,main() 方法有必要吗?答案取决于用户使用的 JDK 版本。

如果用户使用的是 JDK 1.06 或更早版本,静态代码块会在不提及 main() 方法的情况下执行。然而,如果用户使用的是高于 1.06 的 JDK 版本,程序会报错。

请观察以下两个程序。

文件名: StaticBlock4.java

输出

The print statement gets executed without main method.

文件名: StaticBlock5.java

输出

Error: Main method not found in class StaticBlock5, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application