最佳实践:Java 静态非最终变量 [英] Best Practice: Java static non final variables

查看:18
本文介绍了最佳实践:Java 静态非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,什么时候应该使用静态非最终变量?

In Java, when should static non final variables be used?

例如

private static int MY_VAR = 0;

显然我们在这里不是在谈论常量.

Obviously we are not talking about constants here.

public static final int MY_CONSTANT = 1;

根据我的经验,我经常在使用单例时证明它们是合理的,但最终我需要有多个实例,这让我非常头疼并重新分解.

In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.

在实践中使用它们似乎很少见.你怎么看?

It seems it is rare that they should be used in practice. What do you think?

推荐答案

统计收集可能使用非最终变量,例如计算创建的实例数.另一方面,对于这种情况,您可能无论如何都想使用 AtomicLong 等,此时它可以是最终的.或者,如果您要收集多个统计数据,您可能会得到一个 Statistics 类和对其实例的最终引用.

Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics class and a final reference to an instance of it.

拥有(合理地)非最终静态变量当然非常罕见.

It's certainly pretty rare to have (justifiably) non-final static variables.

这篇关于最佳实践:Java 静态非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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