执行顺序

原文: https://javabeginnerstutorial.com/core-java-tutorial/order-of-execution-of-blocks-in-java/

在本文中,我们将学习 Java 中块执行的顺序。

Java 类中的不同块及其执行顺序

  1. 静态块
  2. 初始化块(匿名块)
  3. 构造器
  1. /*
  2. * Here we will learn to see how the different part (Ananymous Block, Constructor and Static Block ) of class will behave
  3. * and what would be the order of execution.
  4. */
  5. class JBTCLass {
  6. /*
  7. * Here Creating the Ananymous Block
  8. */
  9. {
  10. System.out.println("Inside Ananymous Block");
  11. }
  12. /*
  13. * Now Creating the Static Block in Class
  14. */
  15. static {
  16. System.out.println("Inside Static Block");
  17. }
  18. /*
  19. * Here Creating the Constructor of Class
  20. */
  21. JBTCLass() {
  22. System.out.println("Inside Constructor of Class");
  23. }
  24. public static void main(String[] args) {
  25. // Creating the Object of the Class
  26. JBTCLass obj = new JBTCLass();
  27. System.out.println("*******************");
  28. // Again Creating Object of Class
  29. JBTCLass obj1 = new JBTCLass();
  30. }
  31. }

上面程序的输出

  1. Inside Static Block
  2. Inside Ananymous Block
  3. Inside COnstructor of Class
  4. *******************
  5. Inside Ananymous Block
  6. Inside COnstructor of Class

如您所见,STATIC块仅在加载类时执行一次。

但是,每当创建一个类的对象时,匿名块和构造器就会运行。 初始化块将首先执行,然后构造器。