欢迎来到我们关于 Java 中 static 关键字系列的第一篇文章!在本系列中,我们将分解各种概念,例如静态变量、方法、嵌套类等,并以简短的文章形式介绍它们,以帮助您轻松掌握这些概念。
在这篇文章中,我们将重点关注静态块——一种特殊功能,用于在类加载期间执行一次代码。您将通过实践示例了解什么是静态块、它们如何工作以及何时使用它们。
静态块是用 static 关键字标记的代码块,当JVM 的 ClassLoader 将类加载到内存中时,仅运行一次。
下面是一个程序,演示了静态块以及构造函数和初始化块的行为以进行比较。
package keywords.static_keyword; public class StaticBlock { public static int constantNumber; private int number; // Static Block: Executes once when the class is loaded. static { constantNumber = 100; System.out.println("Static Block Invoked: " + constantNumber); } // Constructor: Called whenever a new object is created. public StaticBlock() { System.out.println("Default Constructor invoked: " + number); } // Constructor: Called whenever a new object is created. public StaticBlock(int num) { System.out.println("Parameterized Constructor invoked: " + (number + num)); } // Initializer Block: Runs before EVERY constructor call. { System.out.println("Initializer Block Invoked"); number = 60 + constantNumber; } public static void main(String[] args) { // Objects created to observe initializer and constructor behavior. StaticBlock obj1 = new StaticBlock(); StaticBlock obj2 = new StaticBlock(200); } }
输出:
Static Block Invoked: 100 Initializer Block Invoked Default Constructor invoked: 0 Initializer Block Invoked Parameterized Constructor invoked: 260
静态块执行
对象创建和初始化块
构造函数行为
Feature | Static Block | Initializer Block | Constructor |
---|---|---|---|
When Executed | On class loading | Before each constructor call | On object creation |
How Many Times | Once | Every time an object is created | Every time an object is created |
Purpose | Initialize static members | Initialize instance variables | Initialize the object |
Access Restrictions | Can’t access non-static members directly | Can access both static and non-static | Can access both static and non-static |
结论
Java 中的静态块是一个强大的工具,可以
在类加载期间执行一次代码请继续关注即将发布的帖子,我们将探讨与 static 关键字相关的更多基本概念。
以上是Static 关键字:解码 Java 中的静态块的详细内容。更多信息请关注PHP中文网其他相关文章!