为什么使用静态块直接初始化实例变量? [英] Why use static blocks over initializing instance variables directly?

查看:463
本文介绍了为什么使用静态块直接初始化实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我会使用静态块:

Why would I use a static block:

static {
   B = 10;
}

结束:

Integer B = 10;

一方的优势/劣势是什么?

What is the advantages/disadvantages of one over the other?

推荐答案

只有在必要时才应使用静态初始化程序块。例如,有时您需要执行几个步骤来计算字段的最终值。在这种情况下,您有两个机会:编写一个计算值的方法并将您的字段声明为 static final Integer B = calculateB(),或者使用初始化块:

You should only use a static initializer block, when it is necessary. For example, sometimes you need to do several steps to calculate the final value of the field. In this case you have two opportunities: write a method that calculates the value and declare your field as static final Integer B = calculateB(), or use an initializer block:

static final Integer B;
static {
  int temp = ...;
  ...
  B = temp;
}

在这种情况下,我更喜欢静态块,因为方法可能会令人困惑(其他开发人员可能会尝试调用它,虽然它只是在初始化期间调用一次。)

In this case I prefer the static block, because a method might be confusing (other developers might try to call it, although it is only meant to be called once during initialization).

同样适用于实例字段,尽管通常可以避免不寻常的初始化块,只需将字段的初始化逻辑写入构造函数(静态字段当然不可能)。

The same applies for instance fields as well, although normally one would avoid the unusual initialization block and simply write the initialization logic for fields into the constructor (which is of course not possible for static fields).

这篇关于为什么使用静态块直接初始化实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆