I could not find any references online about this. But just wanted to know if final fields in a class should always be static
or is it just a convention. Based on my understanding of their uses, I feel that it is more of a logical thing to do than something that is imposed by the language.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
They don't always come together and it's not a convention.
final
fields are often used to create immutable types:On the other hand
static
but notfinal
fields are not that common and are quite tricky.static final
is seen often because it means application1-wide constant.1 - well, class loader-wide, to be precise
Final fields do not need to be static, and sometimes it can be useful to have a non-static final instance variable. Fields that are marked both static and final are usually used for constants, like this:
However, sometimes you'll see a non-static final field when an object has a immutable property. Usually, non-static
final
fields are still markedprivate
for the usual reasons, though, so it's more of an extra check so the compiler can make sure you're never setting the property again.The answer is no.
static
...meaning there can only be one of this
final
...meaning that this is a constant
No, absolutely not - and it's not a convention.
static
andfinal
are entirely different things.static
means that the field relates to the type rather than any particular instance of the type.final
means that the field can't change value after initial assignment (which must occur during type/instance initialization).static final
fields are usually for constants - whereas instance fields which arefinal
are usually used when creating immutable types.Of course not. They must be static if they belong to the class, and not be static if they belong to the instance of the class:
If you want to access them like
ClassName.FIELD
, then yes, you have to do that. If you don't make it static, you have to do something likenew ClassName().FIELD
, which is unnecessary and a pointless creation of an object.However, if you are only using it in the class or making it
private
, then don't make it static. If you are within the actual class, you can just doFIELD
.To fully grasp this concept, you have to know what
static
means. Static means that it belongs to the actual class, not an instance of it.