执行顺序
原文: https://javabeginnerstutorial.com/core-java-tutorial/order-of-execution-of-blocks-in-java/
在本文中,我们将学习 Java 中块执行的顺序。
Java 类中的不同块及其执行顺序
- 静态块
- 初始化块(匿名块)
- 构造器
/** Here we will learn to see how the different part (Ananymous Block, Constructor and Static Block ) of class will behave* and what would be the order of execution.*/class JBTCLass {/** Here Creating the Ananymous Block*/{System.out.println("Inside Ananymous Block");}/** Now Creating the Static Block in Class*/static {System.out.println("Inside Static Block");}/** Here Creating the Constructor of Class*/JBTCLass() {System.out.println("Inside Constructor of Class");}public static void main(String[] args) {// Creating the Object of the ClassJBTCLass obj = new JBTCLass();System.out.println("*******************");// Again Creating Object of ClassJBTCLass obj1 = new JBTCLass();}}
上面程序的输出
Inside Static BlockInside Ananymous BlockInside COnstructor of Class*******************Inside Ananymous BlockInside COnstructor of Class
如您所见,STATIC块仅在加载类时执行一次。
但是,每当创建一个类的对象时,匿名块和构造器就会运行。 初始化块将首先执行,然后构造器。
