【问题标题】:What is the difference between initializing a static variable when it is declared vs initializing it in a static block? [duplicate]在声明时初始化静态变量与在静态块中初始化它有什么区别? [复制]
【发布时间】:2021-06-24 06:41:20
【问题描述】:

我在下面的链接中,在第 5 步,在服务定位器设计模式指南中发现了这种用法 https://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm

我不明白他们为什么使用这种结构。

public class ServiceLocator {
   private static Cache cache;

   static {
      cache = new Cache();      
   }
}

   private static Cache cache = new Cache();

【问题讨论】:

    标签: java variables initialization declaration


    【解决方案1】:

    在这种特殊情况下,结果完全相同。如果您需要应用更多逻辑而不仅仅是简单的字段初始化,您可以使用静态块。

    如果你想提高代码的可读性,你应该初始化一个静态变量:

    private static Cache cache = new Cache();
    

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多