私有最终字段也应该是静态的吗? [英] Should a private final field be static too?

查看:55
本文介绍了私有最终字段也应该是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果我的班级中有此字段: private final int foo = ... ,是否应该将其放在静态 private static final int foo = ...?因为如果它是静态的,则对于我的类的所有实例都是通用的,并且永远不会改变.

I was wondering, if I have this field in my class : private final int foo = ..., should I put it in static private static final int foo = ...? Because if it's static, it's common to all the instances of my class, and will never change.

是否有理由不将其置于静态状态?还是我必须将其置于静态状态?

Is there a reason to not put it in static? Or do I have to put it in static?

推荐答案

如果类的每个实例的foo都应具有 same 不变值,则应使foo为final和static.如果您的类的每个实例可以为foo分配一个不同(但仍然是不变的)值,则该值应该只是最终值.

If every instance of your class should have the same immutable value for foo, then you should make foo final and static. If each instance of your class can have a different (but still immutable) value for foo, then the value should just be final.

但是,如果类的每个实例对于foo应该具有相同的不可变值,则它实际上是一个常量.按照惯例,通常编码如下:

However, if every instance of your class should have the same immutable value for foo, then it is a really a constant. By convention, that is typically coded as follows:

private static final int FOO = ...

请注意大写字母表示常量...

Note the caps to denote a constant...

这篇关于私有最终字段也应该是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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